自定义异常类:
class MyException:Exception { public MyException(int a,int b) { this.i = a; this.j = b; } private int i; private int j; public override string Message { get { return "输入值不能小于0"; } } public override string ToString() { return base.ToString()+" My error"; } }
使用异常类的函数:
class MyClass { public void SetScale(int a,int b) { if (a < 0 || b < 0) { throw new MyException(a, b); } else { Console.WriteLine(a+b); } } }
使用try catch捕获异常:
class Program { static void Main(string[] args) { try { function(); } catch (MyException ex) { Console.WriteLine(ex.Message); } finally { Console.ReadLine(); } } static private void function() { MyClass m = new MyClass(); int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("回车后计算"); Console.ReadLine(); m.SetScale(a, b); } }