__try and try/catch/finally in C
In C , exception handling is primarily achieved through the try/catch/finally blocks. However, there are lesser-known commands that start with double underscores, such as __try. This article aims to clarify when these underscores are necessary.
On Windows systems, exceptions are supported through Structured Exception Handling (SEH), an operating system-level mechanism. Compilers typically utilize this SEH infrastructure for C exception implementation. The throw and catch keywords solely handle C exceptions, with their corresponding SEH exception code being 0xe06d7363.
To handle SEH exceptions, C programs require the use of the non-standard __try keyword. Additionally, __except is similar to catch but allows for specifying an exception filter to determine if an active exception should be handled. __finally enables code execution after exception handling.
To illustrate these concepts, consider the example program below:
#include <windows.h> #include <iostream> class Example { public: ~Example() { std::cout << "destructed" << std::endl; } }; int filterException(int code, PEXCEPTION_POINTERS ex) { std::cout << "Filtering " << std::hex << code << std::endl; return EXCEPTION_EXECUTE_HANDLER; } void testProcessorFault() { Example e; int* p = 0; *p = 42; } void testCppException() { Example e; throw 42; } int main() { __try { testProcessorFault(); } __except(filterException(GetExceptionCode(), GetExceptionInformation())) { std::cout << "caught" << std::endl; } __try { testCppException(); } __except(filterException(GetExceptionCode(), GetExceptionInformation())) { std::cout << "caught" << std::endl; } return 0; }
The above is the detailed content of When Should You Use `__try` and `__except` Instead of `try` and `catch` in C ?. For more information, please follow other related articles on the PHP Chinese website!