try-catch-finally (C# 參考)
更新:2007 年 11 月
catch 與 finally 常一起使用於獲得與使用 try 區塊中的資源、處理 catch 區塊中的例外狀況,以及釋放 finally 區塊中的資源時。
如需重新擲回例外狀況的詳細資訊和範例,請參閱 try-catch 和擲回例外狀況。
範例
public class EHClass
{
void ReadFile(int index)
{
// To run this code, substitute a valid path from your local machine
string path = @"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do something with buffer...
}
}
C# 語言規格
如需詳細資料,請參閱 C# 語言規格中的下列章節:
5.3.3.15 try-catch-finally 陳述式
8.10 try 陳述式
16 例外狀況
請參閱
工作
概念
參考
The try, catch, and throw Statements