如何使用 try/catch 區塊攔截例外狀況How to use the try/catch block to catch exceptions

將任何可能引發或擲回例外狀況的程式碼陳述式放置於 try 區塊,並將用來處理例外狀況的陳述式放置於 try 區塊之下的一或多個 catch 區塊中。Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. 每個 catch 區塊都會包含例外狀況類型,而且可以包含處理該例外狀況類型所需的其他陳述式。Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

在下列範例中,StreamReader 開啟名為 data.txt 的檔案,並從該檔案擷取了一行。In the following example, a StreamReader opens a file called data.txt and retrieves a line from the file. 因為程式碼可能會擲回三個例外狀況的任何一個,所以將其放置於 try 區塊。Since the code might throw any of three exceptions, it's placed in a try block. 三個 catch 區塊可以藉由將結果顯示給主控台,來攔截例外狀況並加以處理。Three catch blocks catch the exceptions and handle them by displaying the results to the console.

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 區塊未處理的例外狀況。The Common Language Runtime (CLR) catches exceptions not handled by catch blocks. 如果 CLR 攔截了例外狀況,可能會發生下列其中一種結果,視您的 CLR 組態而有所不同:If an exception is caught by the CLR, one of the following results may occur depending on your CLR configuration:

  • [偵錯] 對話方塊隨即出現。A Debug dialog box appears.
  • 程式停止執行,內容為例外狀況資訊的對話方塊隨即出現。The program stops execution and a dialog box with exception information appears.
  • 錯誤會輸出至標準錯誤輸出資料流An error prints out to the standard error output stream.

注意

多數程式碼可以擲回例外狀況,而且某些例外狀況 (例如 OutOfMemoryException) 可能在任何時間由 CLR 本身擲回。Most code can throw an exception, and some exceptions, like OutOfMemoryException, can be thrown by the CLR itself at any time. 雖然應用程式不必處理這些例外狀況,但是請在撰寫供他人使用的程式庫時注意其發生的可能性。While applications aren't required to deal with these exceptions, be aware of the possibility when writing libraries to be used by others. 如需何時在 try 區塊中設定程式碼的建議,請參閱例外狀況的最佳做法For suggestions on when to set code in a try block, see Best Practices for Exceptions.

另請參閱See also

例外狀況Exceptions
在 .NET 中處理 I/O 錯誤Handling I/O errors in .NET