Catching exceptions thrown without try/catch
I recall reading about how exceptions could be caught without the use of try/catch. Basically when an exception is thrown such as "Unhandled exception" via derefencing开发者_JS百科 a null pointer, there would be a process that is triggered even when a try/catch is not coded for the exception. I believe it had something to do with a top level library that you write then include in your code. Unfortunately documentation on such a method seems to be non-existent but I have seen/heard of such a method being done before. Could someone please explain how this is done?
In C++, dereferencing a null pointer causes undefined behavior, which does not necessarily imply that an exception is thrown. On Unix systems, for example, a SIGSEGV signal is raised instead.
On Windows, access violations raise a SEH exception. SEH exceptions are not the same as C++ exception; they are handled using __try/__except
statements (as opposed to try/catch
statements). An unhandled SEH exception invokes unhandled exception filter, which you can set using SetUnhandledExceptionFilter
.
#include <Windows.h>
#include <iostream>
LONG WINAPI MyFilter(EXCEPTION_POINTERS * /*ExceptionInfo*/)
{
std::cout << "An uncaught exception was detected!\n";
// Ultimately causes Windows Error Reporting to be invoked.
// Use EXCEPTION_EXECUTE_HANDLER to silently terminate the application.
return EXCEPTION_CONTINUE_SEARCH;
}
int main()
{
SetUnhandledExceptionFilter(MyFilter);
*(char volatile *)0 = 0;
}
You may be thinking of the Windows Structured Exception Handling mechanism. With full C++ try/catch semantics supported, I personally haven't found any reasonable use case for it.
That's an operating system implementation detail, dereferencing a null pointer doesn't generate a C++ exception. On Windows that generates an SEH exception, the MSVC compiler lets you handle them with the non-standard __try and __except keywords. On *nix that generates a signal, you use the functions in the signal.h header file.
精彩评论