catch 和 finally 一起使用的常见方式是:在 try 块中获取并使用资源,在catch 块中处理异常情况,并在finally 块中释放资源。
finally 块用于清除 try 块中分配的任何资源,以及运行任何即使在发生异常时也必须执行的代码。控制总是传递给 finally 块,与 try 块的退出方式无关。
// try_catch_finally.cs using System; public class EHClass { static void Main() { try { Console.WriteLine("Executing the try statement."); throw new NullReferenceException(); } catch (NullReferenceException e) { Console.WriteLine("{0} Caught exception #1.", e); } catch { Console.WriteLine("Caught exception #2."); } finally { Console.WriteLine("Executing finally block."); } } }
示例输出
Executing the try statement. System.NullReferenceException: Object reference not set to an instance of an object. at EHClass.Main() Caught exception #1. Executing finally block.