C# try-catch处理异常
使用try-catch进行异常处理,下面是两个小例子:
两个例子中没有写finally语句
finally的作用是无论有无异常,finally下的语句都会执行。
//简单的处理异常
namespace _20200323 { class Program { static void Main(string[] args) { string a = Console.ReadLine(); string b = Console.ReadLine(); Calculator cal = new Calculator(); int ad = cal.Add(a, b); Console.WriteLine(ad); } } class Calculator { public int Add(string argu1, string argu2) { int a = 0; int b = 0; try { a = int.Parse(argu1); b = int.Parse(argu2); } catch { Console.WriteLine("输入数据有误"); } int result = a + b; return result; } } }
//精细的处理异常
namespace _20200323 { class Program { static void Main(string[] args) { string a = Console.ReadLine(); string b = Console.ReadLine(); Calculator cal = new Calculator(); int ad = cal.Add(a, b); Console.WriteLine(ad); } } class Calculator { public int Add(string argu1, string argu2) { int a = 0; int b = 0; try { a = int.Parse(argu1); b = int.Parse(argu2); } catch(ArgumentException) { Console.WriteLine("输入数据为null"); } catch(FormatException) { Console.WriteLine("输入的不是数字"); } catch(OverflowException) { Console.WriteLine("超出值的范围"); } int result = a + b; return result; } } }