static void TestCatch2()
{
System.IO.StreamWriter sw = null;
try
{
sw = new System.IO.StreamWriter(@"C:testtest.txt");
sw.WriteLine("Hello");
}
catch (System.IO.FileNotFoundException ex)
{
// Put the more specific exception first.
System.Console.WriteLine(ex.ToString());
}
catch (System.IO.IOException ex)
{
// Put the less specific exception last.
System.Console.WriteLine(ex.ToString());
}
finally
{
sw.Close();
}
System.Console.WriteLine("Done");
}
执行 catch 块之前,运行时会检查 finally 块。 Finally 块使程序员能够清除中止的 try 块可能遗留下的任何模糊状态,或者释放任何外部资源(例如图形句柄、数据库连接或文件流),而无需等待运行时中的垃圾回收器终结这些对象。 例如:
static void TestFinally()
{
System.IO.FileStream file = null;
//Change the path to something that works on your machine.
System.IO.FileInfo fileInfo = new System.IO.FileInfo(@"C:file.txt");
try
{
file = fileInfo.OpenWrite();
file.WriteByte(0xF);
}
finally
{
// Closing the file allows you to reopen it immediately - otherwise IOException is thrown.
if (file != null)
{
file.Close();
}
}
try
{
file = fileInfo.OpenWrite();
System.Console.WriteLine("OpenWrite() succeeded");
}
catch (System.IO.IOException)
{
System.Console.WriteLine("OpenWrite() failed");
}
}
如果 WriteByte() 引发了异常,那么在没有调用 file.Close() 的情况下,第二个 try 块中尝试重新打开文件的代码就会失败,并且文件将保持锁定状态。 由于要执行 finally 块(即使已引发异常),前一示例中的 finally 块使得可以正确地关闭文件,从而帮助避免错误。
如果在引发异常之后没有在调用堆栈上找到兼容的 catch 块,则会出现三种情况中的一种:
如果异常出现在析构函数中,则中止该析构函数并调用基析构函数(如果有)。
如果调用堆栈包含静态构造函数或静态字段初始值设定项,则引发一个 TypeInitializationException,并将原始异常分配给新异常的 InnerException 属性。
如果到达线程的开头,则终止线程。
注:相关教程知识阅读请移步到c#教程频道。










