try、throw 和 catch 陳述式 (C++)try, throw, and catch Statements (C++)

若要C++在中執行例外狀況處理,您可以使用trythrowcatch運算式。To implement exception handling in C++, you use try, throw, and catch expressions.

首先,請使用try區塊來括住一個或多個可能會擲回例外狀況的語句。First, use a try block to enclose one or more statements that might throw an exception.

回運算式」會通知try區塊中發生例外狀況(通常是錯誤)。A throw expression signals that an exceptional condition—often, an error—has occurred in a try block. 您可以使用任何類型的物件做為throw運算式的運算元。You can use an object of any type as the operand of a throw expression. 這個物件通常用來傳達與錯誤有關的資訊。Typically, this object is used to communicate information about the error. 在大部分情況下,我們建議您使用std:: exception類別或在標準程式庫中定義的其中一個衍生類別。In most cases, we recommend that you use the std::exception class or one of the derived classes that are defined in the standard library. 如果有任何不適用的類別,建議您從 std::exception 自行衍生例外狀況類別。If one of those is not appropriate, we recommend that you derive your own exception class from std::exception.

若要處理可能擲回的例外狀況,請在try區塊之後立即執行一或多個catch區塊。To handle exceptions that may be thrown, implement one or more catch blocks immediately following a try block. 每個catch區塊都會指定它可以處理的例外狀況類型。Each catch block specifies the type of exception it can handle.

這個範例會顯示try區塊及其處理常式。This example shows a try block and its handlers. 假設 GetNetworkResource() 透過網路連線取得資料,且兩個例外狀況類型是衍生自 std::exception 的使用者定義類別。Assume that GetNetworkResource() acquires data over a network connection and that the two exception types are user-defined classes that derive from std::exception. 請注意,catch 語句中的const參考會攔截到例外狀況。Notice that the exceptions are caught by const reference in the catch statement. 建議您依照值擲回例外狀況並依 const 參考攔截這些例外狀況。We recommend that you throw exceptions by value and catch them by const reference.

範例Example

MyData md;
try {
   // Code that could throw an exception
   md = GetNetworkResource();
}
catch (const networkIOException& e) {
   // Code that executes when an exception of type
   // networkIOException is thrown in the try block
   // ...
   // Log error message in the exception object
   cerr << e.what();
}
catch (const myDataFormatException& e) {
   // Code that handles another exception type
   // ...
   cerr << e.what();
}

// The following syntax shows a throw expression
MyData GetNetworkResource()
{
   // ...
   if (IOSuccess == false)
      throw networkIOException("Unable to connect");
   // ...
   if (readError)
      throw myDataFormatException("Format error");
   // ...
}

備註Remarks

Try子句之後的程式碼是程式碼的保護區段。The code after the try clause is the guarded section of code. Throw運算式會擲回(也就是引發)例外狀況。The throw expression throws—that is, raises—an exception. Catch子句之後的程式碼區塊是例外狀況處理常式。The code block after the catch clause is the exception handler. 如果 throw 和catch運算式中的類型相容,則此處理程式會攔截*擲***回的例外狀況。This is the handler that catches the exception that's thrown if the types in the throw and catch expressions are compatible. 如需管理catch區塊中類型相符的規則清單,請參閱如何評估 catch 區塊For a list of rules that govern type-matching in catch blocks, see How Catch Blocks are Evaluated. 如果catch語句指定了省略號(...),而不是類型,則catch區塊會處理每種類型的例外狀況。If the catch statement specifies an ellipsis (...) instead of a type, the catch block handles every type of exception. 當您使用/eha選項進行編譯時,這些可能包括 C 結構化例外狀況和系統產生或應用程式產生的非同步例外狀況,例如記憶體保護、零除和浮點違規。When you compile with the /EHa option, these can include C structured exceptions and system-generated or application-generated asynchronous exceptions such as memory protection, divide-by-zero, and floating-point violations. 由於catch區塊會在程式順序中進行處理,以尋找相符的類型,因此,省略號處理常式必須是相關聯之try區塊的最後一個處理常式。Because catch blocks are processed in program order to find a matching type, an ellipsis handler must be the last handler for the associated try block. 使用 catch(...) 時請小心;除非 catch 區塊知道如何處理所攔截到的特定例外狀況,否則不可允許程式繼續執行。Use catch(...) with caution; do not allow a program to continue unless the catch block knows how to handle the specific exception that is caught. 通常,catch(...) 區塊的用途是在程式停止執行之前記錄錯誤和執行特殊清除。Typically, a catch(...) block is used to log errors and perform special cleanup before program execution is stopped.

沒有運算元的 throw 運算式會重新回目前正在處理的例外狀況。A throw expression that has no operand re-throws the exception currently being handled. 重新擲回例外狀況時,建議使用此表單,因為其中保留了原始例外狀況的多型類型資訊。We recommend this form when re-throwing the exception, because this preserves the original exception’s polymorphic type information. 這類運算式只能用在catch處理常式或從catch處理常式所呼叫的函式中。Such an expression should only be used in a catch handler or in a function that's called from a catch handler. 重新擲回的例外狀況物件是原始的例外狀況物件,而不是複本。The re-thrown exception object is the original exception object, not a copy.

try {
   throw CSomeOtherException();
}
catch(...) {
   // Catch all exceptions - dangerous!!!
   // Respond (perhaps only partially) to the exception, then
   // re-throw to pass the exception to some other handler
   // ...
   throw;
}

另請參閱See also

例外C++狀況和錯誤處理的現代化最佳做法Modern C++ best practices for exceptions and error handling
關鍵字Keywords
未處理的 C++ 例外狀況Unhandled C++ Exceptions
__uncaught_exception__uncaught_exception