Structured Exception Handling

The __try/__except and __try/__finally statements are a Microsoft extension to the C language that enables applications to gain control of a program after events that would normally terminate execution.

Note   Structured exception handling works with C and C++ source files. However, it is not specifically designed for C++. Although destructors for local objects will be called if you use structured exception handling in a C++ program (if you use the /GX compiler option), you can ensure that your code is more portable by using C++ exception handling. The C++ exception handling mechanism is more flexible, in that it can handle exceptions of any type.

For more information, see The try-except Statement and The try-finally Statement in the C Language Reference.

Syntax

try-except-statement :

__try compound-statement
__except ( expression ) compound-statement

try-finally-statement :

__try compound-statement
__finally compound-statement

If you have C modules that use structured exception handling, they can be mixed with C++ modules that use C++ exception handling. When a C (structured) exception is raised, it can be handled by the C handler, or it can be caught by a C++ catch handler, whichever is dynamically closest to the exception context. One of the major differences between the two models is that when a C exception is raised, it is always of type unsigned int, whereas a C++ exception can be of any type. That is, C exceptions are identified by an unsigned integer value, whereas C++ exceptions are identified by data type. However, while a C++ catch handler can catch a C exception (for example, via an “ellipsis” catch handler), a C exception can also be handled as a typed exception by using a C exception wrapper class. By deriving from this class, each C exception can be attributed a specific derived class.

To use a C exception wrapper class, you install a custom C exception translator function which is called by the internal exception handling mechanism each time a C exception is thrown. Within your translator function, you can throw any typed exception, which can be caught by an appropriate matching C++ catch handler. To specify a custom translation function, call the _set_se_translator function with the name of your translation function as its single argument.