What are the implications of mixing exception handling models in Visual Studio 2010?

I have a third-party static library built with Enable C++ Exceptions set to No ( /EH flag is not specified). What are the consequences of calling code created using C ++ ( /EHa ) exceptions in it? If a Structured Exception is thrown from the library, will the function provided by the _set_se_translator main application be reliably called? (My experiments show that this will happen, but just wondering if this is defined behavior).

Are there any other considerations when mixing exception /EH handling models?

+6
source share
2 answers

Calling code in , which has no permitted exceptions, should not cause any problems - this is no different from calling an external C function or something like that.

Calling a code from that does not have allowed exceptions (to code with the exception turned on) will probably not contain the correct semantics of erasing the stack in the disabled exception code, which means that you will violate the invariants of this code, unless it was specifically designed for work with exceptions. (For example, some libraries (for example, ANTLR) allocate all the memory in the block and delete the user code each time, allowing exceptions to be thrown without leakage, even if they themselves do not use exceptions).

Raymond Chen has a pretty article on how C ++ exception handling works on MSVC ++. In short, it is built on top of Windows SEH. Therefore, it should behave similarly to what happens if you throw a SEH exception in, for example, C. (However, I did not check it myself)

+5
source

According to MSDN then you can mix / EHa and / EHsc :

Two exception handling models, synchronous and asynchronous, are fully compatible and can be mixed in one application.

But there seems to be an exception to this rule, namely when passing exceptions from unmanaged (/ EHsc) to managed (/ clr) , Managed Codes catch all exceptions using structured exception handling (SEH), and this causes unmanaged destructors that cannot be called when unwinding a stack. There are various ways to solve the problem:

  • Change the unmanaged code to use / EHa instead of / EHsc. It has the drawback that catch (...) in unmanaged code will suddenly catch access violations and other crazy things.
  • Create a try-catch block inside unmanaged code and make sure that no exceptions are thrown between the unmanaged world and the managed world.

    2.1. A possible middle road is to ensure that destructors are not called when passing exceptions from the unmanaged to the managed world. Within unmanaged code, create a try-catch wrapper, and then in the catch block, throw the exception into a managed world.

+4
source

Source: https://habr.com/ru/post/891659/


All Articles