.NET Framework 使用finally块
示例
不论是否发生异常finally{...},atry-finally或a的块try-catch-finally始终执行(StackOverflowException抛出a或调用时除外)。Environment.FailFast()
它可以用来安全地释放或清除try{...}块中获取的资源。
Console.Write("请输入文件名: ");
string filename = Console.ReadLine();
Stream fileStream = null;
try
{
fileStream = File.Open(filename);
}
catch (FileNotFoundException)
{
Console.WriteLine("File '{0}' could not be found.", filename);
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}