共用方式為


Syntax of Exception Handlers

OverviewHow Do IFAQ

The structure for C exception handlers is:

__try {

statement-block-1
}
__except (filter) {
    statement-block-2
}

The statements in statement-block-1 are executed unconditionally. During execution of statement-block-1, the exception handler defined by filter and statement-block-2 is active (it becomes the current exception handler).

If an exception occurs during execution of statement-block-1, including any function called directly or indirectly, the system gives control to the current exception handler — unless a handler with higher precedence takes control.

For example, in the following code, the first exception is handled by the outer block, because it is outside the scope of the inner __try block. The second exception is handled by the inner block, which takes precedence.

__try {
    float x, y=0;
    x = 5 / y;        // This exception handled by outer block
    __try {
        x = 0;
        y = 27 / x;   // This exception handled by inner block
    }
    __except( GetExceptionCode() == STATUS_FLOATING_DIVIDE_BY_ZERO) {
        printf("handled by inner block");
    }
}
__except( GetExceptionCode() == STATUS_FLOATING_DIVIDE_BY_ZERO ) {
    printf( "handled by outer block" );
}

This code shows an example of nested exception handlers. Note that calling a function that has a try-except block has the same effect as nesting; the try-except block in the most recently called function takes precedence.

When an exception handler takes control, the system first evaluates the filter. One of the powerful features of structured exception handling is that although filter is evaluated out of normal program sequence (often during execution of another function), filter can refer to local variables within its scope just as any C expression. After filter is evaluated, the next action depends on the value returned.

Value of filter Description
EXCEPTION_CONTINUE_SEARCH (0) Passes control to exception handler with next highest precedence. The handler has declined to recognize the exception.
EXCEPTION_CONTINUE_EXECUTION( –1) Dismisses exception, and continues execution at the location where the exception was raised.
EXCEPTION_EXECUTE_HANDLER (1) Handles exception by executing statements in statement-block-2. Execution then falls through to the end of this statement block.

If the value of filter is EXCEPTION_EXECUTE_HANDLER, execution does not resume where the exception was raised, but falls through to the end of statement-block-2 after it is executed. All blocks and function calls nested inside statement-block-1 are terminated before statement-block-2 is entered.