The following example shows a version of the standard C strcpy function that can handle an invalid pointer and return NULL if one is encountered.
Note that this exception handler is intended to handle an access-violation exception, but is inappropriate if some other type of exception occurs. Therefore, the filter expression in the example uses the GetExceptionCode function to check the exception type before executing the handler. This enables the system to continue its search for an appropriate handler if some other type of exception occurs.
Note also that there is no problem with using a return statement in the try block of a try-except statement. This differs from the use of return in the try block of a try-finally statement, which causes an abnormal termination of the try block.
LPTSTR SafeStrcpy(LPTSTR lpszString1, LPTSTR lpszString2) {
try {
return strcpy(string1, string2);
}
except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER :
EXCEPTION_CONTINUE_SEARCH ) {
return NULL;
}
}
The following example shows the interaction of nested try-finally and try-except statements. The RaiseException function causes an exception in the guarded body of a try-finally termination handler that is inside the guarded body of a try-except exception handler. The exception causes the system to evaluate the FilterFunction function, whose return value in turn causes the exception handler to be invoked. However, before the exception-handler block is executed, the finally block of the termination handler is executed because the flow of control has left the try block of the termination handler.
DWORD FilterFunction() {
printf("1 "); // printed first
return EXCEPTION_EXECUTE_HANDLER;
}
VOID main(VOID) {
try {
try {
RaiseException(1, // exception code
0, // continuable exception
0, NULL); // no arguments
}
finally {
printf("2 ") // this is printed second
}
}
except ( FilterFunction() ) {
printf("3\n"); // this is printed last
}
}