例外狀況和例外處理 (C# 程式設計手冊)Exceptions and Exception Handling (C# Programming Guide)

C# 語言的例外狀況處理功能可協助您處理在程式執行時發生的任何未預期或例外狀況。The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. 例外狀況處理會使用 trycatchfinally 關鍵字來嘗試可能失敗的動作,以便在您決定這樣做很合理時處理失敗,之後再清除資源。Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. 例外狀況可以由 Common Language Runtime (CLR)、.NET Framework 或任何協力廠商程式庫,或者應用程式程式碼來產生。Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. 例外狀況是使用 throw 關鍵字所建立。Exceptions are created by using the throw keyword.

在許多情況下,例外狀況可能不是由您的程式碼直接呼叫的方法所擲回,而是由呼叫堆疊中更下方的另一個方法所擲回。In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. 發生這種情況時,CLR 將回溯堆疊,針對特定的例外狀況型別尋找具有 catch 區塊的方法,而它將會執行第一個這類 catch 區塊 (如果找到)。When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. 如果在呼叫堆疊中的任何地方都找不到適當的 catch 區塊,它將會終止處理序,並向使用者顯示一則訊息。If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user.

在此範例中,方法會測試除數為零,並攔截錯誤。In this example, a method tests for division by zero and catches the error. 如果沒有例外狀況處理,此程式就會終止並產生 DivideByZeroException 未處理的錯誤。Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.

class ExceptionTest
{
    static double SafeDivision(double x, double y)
    {
        if (y == 0)
            throw new System.DivideByZeroException();
        return x / y;
    }
    static void Main()
    {
        // Input for test purposes. Change the values to see
        // exception handling behavior.
        double a = 98, b = 0;
        double result = 0;

        try
        {
            result = SafeDivision(a, b);
            Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("Attempted divide by zero.");
        }
    }
}

例外狀況概觀Exceptions Overview

例外狀況具有下列屬性:Exceptions have the following properties:

  • 例外狀況是最終全都衍生自 System.Exception 的型別。Exceptions are types that all ultimately derive from System.Exception.

  • 在可能擲回例外狀況的陳述式前後使用 try 區塊。Use a try block around the statements that might throw exceptions.

  • 一旦 try 區塊中發生例外狀況之後,控制流程就會跳至第一個相關聯的例外狀況處理常式,此處理常式存在於呼叫堆疊中的任何位置。Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. 在 C# 中,catch 關鍵字是用來定義例外狀況處理常式。In C#, the catch keyword is used to define an exception handler.

  • 如果沒有指定例外狀況的例外狀況處理常式存在,程式就會停止執行並出現錯誤訊息。If no exception handler for a given exception is present, the program stops executing with an error message.

  • 除非您可以處理它,否則不要攔截例外狀況,並讓應用程式保持已知的狀態。Do not catch an exception unless you can handle it and leave the application in a known state. 如果您攔截 System.Exception,請在 catch 區塊結尾使用 throw 關鍵字重新擲回它。If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.

  • 如果 catch 區塊定義了例外狀況變數,您可以使用它來取得所發生例外狀況型別的詳細資訊。If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.

  • 例外狀況可以透過程式使用 throw 關鍵字明確地產生。Exceptions can be explicitly generated by a program by using the throw keyword.

  • 例外狀況物件包含錯誤的詳細資訊,例如呼叫堆疊的狀態和錯誤狀態的文字描述。Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.

  • 即使擲回例外狀況,finally 區塊中的程式碼也會執行。Code in a finally block is executed even if an exception is thrown. 使用 finally 區塊來釋放資源,例如,關閉已在 try 區塊中開啟的任何資料流或檔案。Use a finally block to release resources, for example to close any streams or files that were opened in the try block.

  • .NET Framework 中的 Managed 例外狀況是在 Win32 結構化例外狀況處理機制上實作的。Managed exceptions in the .NET Framework are implemented on top of the Win32 structured exception handling mechanism. 如需詳細資訊,請參閱結構化例外狀況處理 (C/C++)深入探究 Win32 結構化例外狀況處理的毀損課程 (英文)For more information, see Structured Exception Handling (C/C++) and A Crash Course on the Depths of Win32 Structured Exception Handling.

請參閱下列主題,以了解例外狀況和例外狀況處理的詳細資訊:See the following topics for more information about exceptions and exception handling:

C# 語言規格C# Language Specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

請參閱See Also