Home > Backend Development > C++ > body text

When Should You Use `__try` and `__except` Instead of `try` and `catch` in C ?

DDD
Release: 2024-11-07 22:22:03
Original
371 people have browsed it

When Should You Use `__try` and `__except` Instead of `try` and `catch` in C  ?

__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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!