6 - 异常捕获

开始学习 C# 脚本语言,为 Unity 学习奠定基础。这次学习的是 C# 中有关异常捕获的内容。

作用

如果程序在运行时出现不合法的内容,程序就会抛出异常。通过捕获异常并处理,可以增强程序的健壮性。

基本语法

异常捕获的基本语法如下:

   
// 必备部分 try { // 希望进行异常捕获的代码块 } catch (Exception e) { // 在这里处理捕获的异常e } // 可选部分 finally { // 不管有没有捕获到异常, // 均会最后执行 }

实践

例如使用 int.Parse(str) 强转格式时,处理 str 不合理的异常:

   
try { string str = "啊?"; int i = int.Parse(str); } catch (Exception e) { Console.WriteLine("str格式错误,异常名称:"); Console.WriteLine(e); } // str格式错误,异常名称: // System.FormatException: The input string '啊?' was not in a correct format. // ...

参考资料