Exception-Handler Syntax

The try and except keywords are used to construct a frame-based exception handler. The following example shows the structure of a try-except exception handler.

try {

// guarded body of code

}

except (filter-expression) {

// exception-handler block

}

Note that the try block and the exception-handler block require braces ({}). Using a goto statement to jump into the body of a try block or into an exception-handler block is not permitted. This rule applies to both try-except and try-finally statements.

The try block contains the guarded body of code that the exception handler protects. A function can have any number of try-except statements, and these exception-handling statements can be nested within the same function or in different functions. If an exception occurs within the try block, the system takes control and begins the search for an exception handler. For a detailed description of this search, see Exception Handling.

The exception handler receives only exceptions that occur within a single thread. This means that if a try block contains a call to the CreateProcess or CreateThread function, exceptions that occur within the new process or thread are not dispatched to this handler.

The system evaluates the filter expression of each exception handler guarding the code in which the exception occurred until either the exception is handled or there are no more handlers. A filter expression must be evaluated as one of the three following values.

Value Meaning
EXCEPTION_EXECUTE_HANDLER  
  The system transfers control to the exception handler, and execution continues in the stack frame in which the handler is found.
EXCEPTION_CONTINUE_SEARCH  
  The system continues to search for a handler.
EXCEPTION_CONTINUE_EXECUTION  
  The system stops its search for a handler and returns control to the point at which the exception occurred. If the exception is noncontinuable, this results in a EXCEPTION_NONCONTINUABLE_EXCEPTION exception.

The filter expression is evaluated in the context of the function in which the try-except statement is located, even though the exception may have occurred in a different function. This means that the filter expression can access the function's local variables. Similarly, the exception-handler block can access the local variables of the function in which it is located.

For more information about filter expressions and filter functions, see Frame-based Exception Handling.