Home > other >  Windows __try/__except doesn't catch raised exceptions
Windows __try/__except doesn't catch raised exceptions

Time:01-24

So I was trying to write something that dereferences an unknown pointer and returns the status of the operation, like this:

int n;
__try {
    n = *(int*)(addr); // The unknown address.
}
__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    printf("Exception caught!\n");
}

Now this code didn't even catch the exception in the first place, so the VS debugger caught it instead. So I got curious and did a simple dry run:

__try {
    RaiseException(EXCEPTION_ACCESS_VIOLATION, NULL, NULL, nullptr);
}
__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    printf("Exception caught!\n");
}

This yielded the same result as the other block of code did. I've written the upper block of code hundreds of times though and I'm really unsure about why __try would suddenly just pretend like it doesn't exist at all. And yes I've checked my compiler settings. They are set to compile with /RTC1.

CodePudding user response:

As @Hans Passant said, the process's debugger can catch the exception prior to a frame-based exception handler(I checked).
The RaiseException lists an exception handler sequence.

  1. The system first attempts to notify the process's debugger, if any.
  2. If the process is not being debugged, or if the associated debugger does not handle the exception, the system attempts to locate a frame-based exception handler by searching the stack frames of the thread in which the exception occurred. The system searches the current stack frame first, then proceeds backward through preceding stack frames.
  3. If no frame-based handler can be found, or no frame-based handler handles the exception, the system makes a second attempt to notify the process's debugger.
  4. If the process is not being debugged, or if the associated debugger does not handle the exception, the system provides default handling based on the exception type. For most exceptions, the default action is to call the ExitProcess function.
  •  Tags:  
  • Related