using System;
namespace ConsoleApplication2
{
// 定义自己的异常,继承自Exception
public class MyException : Exception
{
public override string Message
{
get { return "不是正整数"; }
}
}
public class Computer
{
public int GetMax(int x, int y)
{
if (x < 1 || y < 1)
{
// 抛出异常
throw new MyException();
}
if (x > y)
return x;
else
return y;
}
}
class Program
{
static void Main(string[] args)
{
Computer c = new Computer();
try
{
int max = c.GetMax(0, 100);
}
catch (MyException me)
{
Console.WriteLine(me.Message);
}
}
}
}
运行结果
class Program
{
static void Main(string[] args)
{
Computer computer = new Computer();
computer.GetMax(0, 100);
}
}
class MyException : Exception
{
public MyException()
{
Console.WriteLine("不是正整数。");
}
}
class Computer
{
public int GetMax(int a, int b)
{
if (a < 1 || b < 1)
throw new MyException();
else
return Math.Max(a, b);
}
}