try 區塊需要一或多個相關聯的 catch 區塊,或 finally 區塊,或兩種都要。
try-catch 區塊的目的是為了攔截和處理工作程式碼所產生的例外狀況。 某些例外狀況可在 catch 區塊中處理,並且可以解決問題而不會重新擲回例外狀況;不過,通常您只能用於確保會擲回適當的例外狀況。
擲回例外狀況之後,執行階段會檢查目前的陳述式是否在 try 區塊內。 如果是的話,便會檢查與 try 區塊關聯的任何 catch 區塊,以查看其是否能攔截該例外狀況。 Catch 區塊通常會指定例外狀況類型;如果 catch 區塊的類型與例外狀況或其基底類別的類型相同,catch 區塊便可處理此方法。
finally 陳述式的目的是為了確保在必要時會立即清除物件 (通常是含有外部資源的物件),即使擲回例外狀況也一樣。
infoC# 語言的例外狀況處理功能可協助您處理在程式執行時發生的任何未預期或例外狀況。 例外狀況處理會使用 try、catch 和 finally 關鍵字來嘗試可能失敗的動作,以便在您決定這樣做很合理時處理失敗,之後再清除資源。
使用 try-catch 陳述式來處理錯誤狀況
System.IO.FileStream file = null;
System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
catch (Exception ex)
{
Response.Write(ex.Message); //將錯誤在畫面上印出
}
使用 try-finally 陳述式來釋放配置在 try 區塊中的資源
System.IO.FileStream file = null;
System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
finally
{
if (file != null)
{
file.Close(); //釋放資源
}
}
使用 try-catch-finally 來處理錯誤狀況,並在結束時釋放 try 區塊中使用的資源
System.IO.FileStream file = null;
System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
catch (Exception ex)
{
Response.Write(ex.Message); //將錯誤在畫面上印出
}
finally
{
if (file != null)
{
file.Close(); //釋放資源
}
}
try 陳述式可以包含多個 catch 區塊。 第一個可以處理例外狀況的 catch 陳述式會先執行,接在後面的任何 catch 陳述式不論相容與否,都會予以略過。
System.IO.StreamWriter sw = null;
try
{
sw = new System.IO.StreamWriter(@"C:\test\test.txt");
sw.WriteLine("Hello");
}
catch (System.IO.FileNotFoundException ex)
{
Response.Write(ex.Message);
}
catch (System.IO.IOException ex)
{
Response.Write(ex.Message);
}
finally
{
sw.Close();
}