Dela via


The try, catch, and throw Statements

The following syntax shows a try block and its handlers:

try {
   // code that could throw an exception
}
[ catch (exception-declaration) {
   // code that executes when exception-declaration is thrown
   // in the try block
}
[catch (exception-declaration) {
   // code that handles another exception type
} ] . . . ]
// The following syntax shows a throw expression:
throw [expression]

Remarks

The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. The try, throw, and catch statements implement exception handling. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code that is outside the normal flow of control. The Microsoft C++ compiler implements the C++ exception handling model based on the ANSI C++ standard.

C++ also provides a way to explicitly specify whether a function can throw exceptions. You can use exception specifications in function declarations to indicate that a function can throw an exception. For example, an exception specification throw(...) tells the compiler that a function can throw an exception, but doesn't specify the type, as in this example:

void MyFunc() throw(...) {
   throw 1;
}

For more information, see Exception Specifications.

Note

The Win32 structured exception-handling mechanism works with both C and C++ source files. However, it is not specifically designed for C++. You can ensure that your code is more portable by using C++ exception handling. Also, C++ exception handling is more flexible, in that it can handle exceptions of any type. For C++ programs, it is recommended that you use the C++ exception-handling mechanism (try, catch, throw) described in this topic.

The code after the try clause is the guarded section of code. The throw expression throws (raises) an exception. The code block after the catch clause is the exception handler, and catches (handles) the exception thrown by the throw expression. The exception-declaration statement indicates the type of exception the clause handles. The type can be any valid data type, including a C++ class. If the exception-declaration statement is an ellipsis (...), the catch clause handles any type of exception, including C exceptions and system- or application-generated exceptions such as memory protection, divide by zero, and floating-point violations. Such a handler must be the last handler for its try block.

The operand of throw is syntactically similar to the operand of a return statement.

Execution proceeds as follows:

  1. Control reaches the try statement by normal sequential execution. The guarded section within the try block is executed.

  2. If no exception is thrown during execution of the guarded section, the catch clauses that follow the try block are not executed. Execution continues at the statement after the last catch clause following the associated try block.

  3. If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is created from the object created by the throw operand. (This implies that a copy constructor may be involved.) At this point, the compiler looks for a catch clause in a higher execution context that can handle an exception of the type thrown (or a catch handler that can handle any type of exception). The catch handlers are examined in order of their appearance following the try block. If no appropriate handler is found, the next dynamically enclosing try block is examined. This process continues until the outermost enclosing try block is examined.

  4. If a matching handler is still not found, or if an exception occurs while unwinding, but before the handler gets control, the predefined run-time function terminate is called. If an exception occurs after throwing the exception, but before the unwind begins, terminate is called.

  5. If a matching catch handler is found, and it catches by value, its formal parameter is initialized by copying the exception object. If it catches by reference, the parameter is initialized to refer to the exception object. After the formal parameter is initialized, the process of unwinding the stack begins. This involves the destruction of all automatic objects that were constructed (but not yet destructed) between the beginning of the try block associated with the catch handler and the exception's throw site. Destruction occurs in reverse order of construction. The catch handler is executed and the program resumes execution following the last handler (that is, the first statement or construct which is not a catch handler). Control can only enter a catch handler through a thrown exception, never via a goto statement or a case label in a switch statement.

The following is a simple example of a try block and its associated catch handler. This example detects failure of a memory allocation operation using the new operator. If new is successful, the catch handler is never executed:

// exceptions_trycatchandthrowstatements.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main() {
   char *buf;
   try {
      buf = new char[512];
      if( buf == 0 )
         throw "Memory allocation failure!";
   }
   catch( char * str ) {
      cout << "Exception raised: " << str << '\n';
   }
}

The operand of the throw expression specifies that an exception of type char * is being thrown. It is handled by a catch handler that expresses the ability to catch an exception of type char *. In the event of a memory allocation failure, this is the output from the preceding example:

Exception raised: Memory allocation failure!

The real power of C++ exception handling lies not only in its ability to deal with exceptions of varying types, but also in its ability to automatically call destructor functions during stack unwinding, for all local objects constructed before the exception was thrown.

The following example demonstrates C++ exception handling using classes with destructor semantics:

Example

// exceptions_trycatchandthrowstatements2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void MyFunc( void );

class CTest {
public:
   CTest() {};
   ~CTest() {};
   const char *ShowReason() const { 
      return "Exception in CTest class."; 
   }
};

class CDtorDemo {
public:
   CDtorDemo();
   ~CDtorDemo();
};

CDtorDemo::CDtorDemo() {
   cout << "Constructing CDtorDemo.\n";
}

CDtorDemo::~CDtorDemo() {
   cout << "Destructing CDtorDemo.\n";
}

void MyFunc() {
   CDtorDemo D;
   cout<< "In MyFunc(). Throwing CTest exception.\n";
   throw CTest();
}

int main() {
   cout << "In main.\n";
   try {
       cout << "In try block, calling MyFunc().\n";
       MyFunc();
   }
   catch( CTest E ) {
       cout << "In catch handler.\n";
       cout << "Caught CTest exception type: ";
       cout << E.ShowReason() << "\n";
   }
   catch( char *str )    {
       cout << "Caught some other exception: " << str << "\n";
   }
   cout << "Back in main. Execution resumes here.\n";
}

In main. In try block, calling MyFunc(). Constructing CDtorDemo. In MyFunc(). Throwing CTest exception. Destructing CDtorDemo. In catch handler. Caught CTest exception type: Exception in CTest class. Back in main. Execution resumes here.

Comments

Note that in this example, the exception parameter (the argument to the catch clause) is declared in both catch handlers:

catch( CTest E )
// ...
catch( char *str )
// ...

You do not need to declare this parameter; in many cases it may be sufficient to notify the handler that a particular type of exception has occurred. However, if you do not declare an exception object in the exception-declaration, you will not have access to that object in the catch handler clause.

A throw-expression with no operand re-throws the exception currently being handled. Such an expression should appear only in a catch handler or in a function called from within a catch handler. The re-thrown exception object is the original exception object (not a copy). For example:

try {
   throw CSomeOtherException();
}
catch(...) {  // Handle all exceptions
   // Respond (perhaps only partially) to exception
   throw;       // Pass exception to some other handler
}

See Also

Reference

C++ Exception Handling

C++ Keywords

Function-try Blocks

Unhandled C++ Exceptions

Change History

Date

History

Reason

February 2009

Clarified step 2 of the execution of a try-catch block.

Customer feedback.