如何使用 try/catch 區塊攔截例外狀況

將任何可能引發或擲回例外狀況的程式碼陳述式放置於 try 區塊,並將用來處理例外狀況的陳述式放置於 try 區塊之下的一或多個 catch 區塊中。 每個 catch 區塊都會包含例外狀況類型,而且可以包含處理該例外狀況類型所需的其他陳述式。

在下列範例中,StreamReader 開啟名為 data.txt 的檔案,並從該檔案擷取了一行。 因為程式碼可能會擲回三個例外狀況的任何一個,所以將其放置於 try 區塊。 三個 catch 區塊可以藉由將結果顯示給主控台,來攔截例外狀況並加以處理。

using namespace System;
using namespace System::IO;

public ref class ProcessFile
{
public:
    static void Main()
    {
        try
        {
            StreamReader^ sr = File::OpenText("data.txt");
            Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
            sr->Close();
        }
        catch (Exception^ e)
        {
            Console::WriteLine("An error occurred: '{0}'", e);
        }
    }
};

int main()
{
    ProcessFile::Main();
}
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

通用語言執行平台 (CLR) 會攔截 catch 區塊未處理的例外狀況。 如果 CLR 攔截了例外狀況,可能會發生下列其中一種結果,視您的 CLR 組態而有所不同:

  • [偵錯] 對話方塊隨即出現。
  • 程式停止執行,內容為例外狀況資訊的對話方塊隨即出現。
  • 錯誤會輸出至標準錯誤輸出資料流

注意

多數程式碼可以擲回例外狀況,而且某些例外狀況 (例如 OutOfMemoryException) 可能在任何時間由 CLR 本身擲回。 雖然應用程式不必處理這些例外狀況,但是請在撰寫供他人使用的程式庫時注意其發生的可能性。 如需何時在 try 區塊中設定程式碼的建議,請參閱例外狀況的最佳做法

另請參閱