catch 和 finally 一起使用的常见方式是:在 try 块中获取并使用资源,在 catch 块中处理异常情况,并在 finally 块中释放资源。
有关重新引发异常的更多信息和示例,请参见 try-catch 和“引发异常”。
示例
| 复制代码 |
---|
// 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# 语言规范
请参见