如何:使用 finally 执行清理代码
finally 语句的目的是确保即使在引发异常的情况下也能立即进行必要的对象(通常是保存外部资源的对象)清理。此类清理功能的一个示例是在使用后立即对 FileStream 调用 Close,而不是等待公共语言运行时对该对象进行垃圾回收,如下所示:
static void CodeWithoutCleanup()
{
System.IO.FileStream file = null;
System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt");
file = fileInfo.OpenWrite();
file.WriteByte(0xF);
file.Close();
}
为了将上面的代码转换为 try-catch-finally 语句,需要将清理代码与工作代码分开,如下所示。
static void CodeWithCleanup()
{
System.IO.FileStream file = null;
System.IO.FileInfo fileInfo = null;
try
{
fileInfo = new System.IO.FileInfo("C:\\file.txt");
file = fileInfo.OpenWrite();
file.WriteByte(0xF);
}
catch(System.UnauthorizedAccessException e)
{
System.Console.WriteLine(e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
}