导入
Try...Catch...Finally
学习如何使用 try、catch 和 finally 块处理运行时错误并确保资源清理。
1// 有效的索引:0, 1, 2, 3 2var numbers = new int[] { 1, 2, 3, 4 }; 3 4// 我们试图打印第5个元素 5// 但数组中只有4个元素 6Console.WriteLine(numbers[4]);
try-catch 语句的语法
1try 2{ 3 // 可能引发异常的代码 4} 5catch 6{ 7 // 出现异常时采取的操作 8}
1try 2{ 3 var numbers = new int[] { 1, 2, 3, 4 }; 4 Console.WriteLine(numbers[4]); 5} 6catch 7{ 8 Console.WriteLine("发生了异常。"); 9}
...
try...catch...finally 的执行流程
1try 2{ 3 var numbers = new int[] { 1, 2, 3, 4 }; 4 Console.WriteLine(numbers[4]); 5} 6catch (IndexOutOfRangeException) 7{ 8 Console.WriteLine("你超出了数组的边界。"); 9} 10catch (Exception ex) 11{ 12 Console.WriteLine(ex.Message); 13}
1try 2{ 3 var numbers = new int[] { 1, 2, 3, 4 }; 4 Console.WriteLine(numbers[4]); 5} 6catch (IndexOutOfRangeException) 7{ 8 Console.WriteLine("你超出了数组的边界。"); 9} 10catch (Exception ex) 11{ 12 Console.WriteLine(ex.Message); 13} 14finally 15{ 16 Console.WriteLine("正在释放资源..."); 17}
1try 2{ 3 Console.WriteLine("尝试打开系统资源..."); 4 // 这里发生错误,但我们在此处未捕获 5 throw new Exception("关键资源失败!"); 6} 7finally 8{ 9 // 即使错误未在此处被捕获,此代码也会运行 10 Console.WriteLine("清理:确保资源已安全关闭。"); 11}