將任何可能引發或擲回例外狀況的程式代碼語句放在 try
區塊中,並將用於處理例外狀況的語句放在 catch
區塊下方的一個或多個 try
區塊中。 每個 catch
區塊都包含例外狀況類型,而且可以包含處理該例外狀況類型所需的其他語句。
在下列範例中,會 StreamReader 開啟名為 data.txt的 檔案,並從檔案擷取一行。 因為程式代碼可能會擲回三個例外狀況中的任何一個,所以它會放在 try
一個區塊中。 三 catch
個區塊會擷取例外狀況,並藉由向主控台顯示結果來處理例外狀況。
using System;
using System.IO;
public class ProcessFile
{
public static void Main()
{
try
{
using (StreamReader sr = File.OpenText("data.txt"))
{
Console.WriteLine($"The first line of this file is {sr.ReadLine()}");
}
}
catch (FileNotFoundException e)
{
Console.WriteLine($"The file was not found: '{e}'");
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine($"The directory was not found: '{e}'");
}
catch (IOException e)
{
Console.WriteLine($"The file could not be opened: '{e}'");
}
}
}
Imports System.IO
Public Class ProcessFile
Public Shared Sub Main()
Try
Using sr As StreamReader = File.OpenText("data.txt")
Console.WriteLine($"The first line of this file is {sr.ReadLine()}")
End Using
Catch e As FileNotFoundException
Console.WriteLine($"The file was not found: '{e}'")
Catch e As DirectoryNotFoundException
Console.WriteLine($"The directory was not found: '{e}'")
Catch e As IOException
Console.WriteLine($"The file could not be opened: '{e}'")
End Try
End Sub
End Class
Common Language Runtime (CLR) 會攔截程式碼區塊未處理的例外 catch
。 如果 CLR 攔截到例外狀況,則視您的 CLR 組態而定,可能會發生下列其中一個結果:
- [ 偵錯] 對話框隨即出現。
- 程式會停止執行,並會出現例外狀況資訊的對話框。
- 錯誤會輸出至 標準錯誤輸出流。
備註
大部分的程式代碼都可以擲回例外狀況,而某些例外狀況,例如 OutOfMemoryException,可以隨時由CLR本身擲回。 雖然應用程式不需要處理這些例外,但撰寫供他人使用的函式庫時要注意這一點的可能性。 如需何時在區塊中 try
設定程式碼的建議,請參閱 例外狀況的最佳做法。