Home > Backend Development > C++ > What is the Purpose and Implementation of __try in C on Windows?

What is the Purpose and Implementation of __try in C on Windows?

DDD
Release: 2024-11-07 15:04:02
Original
138 people have browsed it

What is the Purpose and Implementation of __try in C   on Windows?

Understanding __try, try/catch/finally in C

In C , the try/catch/finally blocks are typically used for exception handling. However, there's an alternate syntax with double underscores, __try, which is specific to Windows.

When to Use __try

On Windows, the exception handling is implemented through Structured Exception Handling (SEH). When targeting Windows with MSVC compilers, the __try syntax can be used to catch SEH exceptions.

SEH and C Exceptions

The MSVC compiler generates code that maps C exceptions to the SEH infrastructure, using the exception code 0xe06d7363 ("msc"). This allows C destructors to be called when an SEH exception is raised.

Compiler Optimization for Destructors

The MSVC compiler optimizes the code to avoid generating the destructors code if there's no throw statement within the object's lifetime. This optimization can be suppressed by using the /EHa compile option, which is necessary to catch all SEH exceptions consistently.

SEH Exception Types

SEH has many exception types, including those defined by the operating system and those used by specific applications. Managed exceptions, such as .NET exceptions, use the exception code 0xe0434f4d ("com").

__try, __except, and __finally

To catch SEH exceptions, __try is used in conjunction with __except, which acts like a C catch block but with more capabilities. __finally allows for code to be executed after the exception handling.

Example Code

The provided code demonstrates the use of __try, __except, and __finally to catch both SEH exceptions (caused by accessing a null pointer) and C exceptions (caused by throwing an integer).

The output shows that the destructors are called for both exceptions, and that __except successfully catches the exceptions.

The above is the detailed content of What is the Purpose and Implementation of __try in C on Windows?. 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