try, catch, and throw Statements

C++ Specific —>

C++ exception handling uses the try, catch, and throw statements to 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.

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.

try-block :
trycompound-statement handler-list

handler-list :
handler handler-listopt

handler :
catch ( exception-declaration ) compound-statement

exception-declaration :
type-specifier-list declarator
type-specifier-list abstract-declarator
type-specifier-list
...

throw-expression :
throwassignment-expressionopt

The compound-statement after the try clause is the guarded section of code. The throw-expression “throws” (raises) an exception. The compound-statement 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 a C exception. 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.

Note   Microsoft C++ does not support exception-specifications, as described in section 15.4 of the ANSI C++ draft. In addition, it does not support function-try-block described in section 15 of the ANSI C++ draft.

For more information on C++ exception handling, see Exception Handling Topics (C++). For information on exception handling in general, see Exception Handling: Overview.

END C++ Specific

Example

In the following example, the try block attempts to write the headers. The catch block then handles a specific file exception, and passes all other exceptions on to the outer block with the throw macro:

// Example of the try and catch statements
try
{
      // Write the file header
      file.Write((LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER));
      //
      // Write the DIB header and the bits
      file.WriteHuge(lpBI, dwDIBSize);
}
catch (CFileException* e)
   {
      ::GlobalUnlock((HGLOBAL) hDib);
      throw;
   }

::GlobalUnlock((HGLOBAL) hDib);
   return TRUE;