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.
本文通过一个具体的C#示例介绍了如何使用try、catch和finally块进行有效的异常处理。示例展示了在try块中执行正常操作,catch块中捕获并处理特定异常,以及在finally块中无论是否发生异常都会执行的清理工作。
152

被折叠的 条评论
为什么被折叠?



