https://learn.microsoft.com/en-us/cpp/cpp/structured-excepti...
> Structured exception handling (SEH) is a Microsoft extension to C and C++ to handle certain exceptional code situations, such as hardware faults, gracefully. Although Windows and Microsoft C++ support SEH, we recommend that you use ISO-standard C++ exception handling in C++ code. It makes your code more portable and flexible. However, to maintain existing code or for particular kinds of programs, you still might have to use SEH.
This is a good insight but I feel like stopping the analysis here is a little bit too early. We should also think about what they actually wanted to achieve. Did they actually need all variables to be stable at the point of any memory access? Maybe they want 90% of the benefits at 10% of the cost somehow?
One of the most important optimizations that a compiler can do is keeping a variable in a register and never even bother letting it hit memory in the first place. If every variable must get its own RAM address and the value at that RAM address must be faithful to a variable's "true" value at any given instruction, we should expect our software to slow down by an order of magnitude or two.
People who keep repeating this have only ever either looked at the profiles of zero or one types of programs.
TIL
Mixing C (structured) and C++ exceptions - https://learn.microsoft.com/en-us/cpp/cpp/mixing-c-structure...
Handle structured exceptions in C++ - https://learn.microsoft.com/en-us/cpp/cpp/exception-handling...
For even more fun, Microsoft C++ implementation of setjmp/longjmp calls dtors of lexically scoped objects properly during stack unwinding (when compiled with proper switches) - https://learn.microsoft.com/en-us/cpp/cpp/using-setjmp-longj...
Finally Important caveats from - https://learn.microsoft.com/en-us/cpp/build/reference/eh-exc...
Specifying /EHa and trying to handle all exceptions by using catch(...) can be dangerous. In most cases, asynchronous exceptions are unrecoverable and should be considered fatal. Catching them and proceeding can cause process corruption and lead to bugs that are hard to find and fix.
Even though Windows and Visual C++ support SEH, we strongly recommend that you use ISO-standard C++ exception handling (/EHsc or /EHs). It makes your code more portable and flexible. There may still be times you have to use SEH in legacy code or for particular kinds of programs. It's required in code compiled to support the common language runtime (/clr), for example. For more information, see Structured exception handling.
We recommend that you never link object files compiled using /EHa to ones compiled using /EHs or /EHsc in the same executable module. If you have to handle an asynchronous exception by using /EHa anywhere in your module, use /EHa to compile all the code in the module. You can use structured exception handling syntax in the same module as code that's compiled by using /EHs. However, you can't mix the SEH syntax with C++ try, throw, and catch in the same function.
A customer wanted to know if it was okay to throw a C++ exception from a structured exception.
They explained that they didn’t want to compile their project with the /EHa switch, which instructs the compiler to use the exception-handling model that catches both asynchronous (structured) exceptions as well as synchronous (C++) exceptions. In other words, the catch statement will catch both explicitly thrown C++ exceptions (raised by the throw statement) as well as exceptions generated by the operating system, either due to notifications from the CPU (such as an access violation or divide-by-zero) or explicit calls to RaiseException.
The customer explained that they didn’t want to use /EHa because doing so significantly impairs compiler optimizations and results in larger code size. But on the other hand, they do want to catch the asynchronous (structured) exceptions.
So they had a fiendish plan.
Their fiendish plan is to install an unhandled exception filter which turns around and throws the C++ exception. That way, a structured exception will result in a standard C++ exception, but without the code generation penalties of the /EHa compiler option.
// This clever function is an exception filter that converts // asynchronous exceptions (structured exception handling) // to synchronous exceptions (C++ exceptions).
LONG WINAPI CleverConversion( EXCEPTION_POINTERS* ExceptionInfo) {
auto record = ExceptionInfo->ExceptionRecord;
std::string message;
... build a message based on the exception code and
other parameters ...
throw std::exception(message.c\_str());
}
int sample_function(int* p) { try { printf("About to dereference the pointer %p\n", p); return *p; } catch (std::exception& e) { Log(e.what()); } return 0; }
int __cdecl main(int argc, char **argv) { SetUnhandledExceptionFilter(CleverConversion);
return sample\_function(nullptr);
}
Neat trick, huh? All the benefits of /EHa without the overhead!
Well, except that they found that it didn’t always work.
In the example above, the catch did catch the C++ exception, but if they took out the printf, then the exception was not caught.
int sample_function(int* p) { try { return *p; } catch (std::exception& e) { Log(e.what()); // exception not caught! } return 0; }
The customer wanted to know why the second version didn’t work.
Actually the first version isn’t guaranteed to work either. It happens to work because the compiler must consider the possibility that the printf function might throw a C++ exception. The printf function is not marked as noexcept, so the possibility is in play. (Not that you’d expect it to be marked as such, seeing as it’s a C function, and C doesn’t have exceptions.) When the access violation is raised as a structured exception, the CleverConversion function turns it into a C++ exception and throws it, at which point the try block catches it. But the try block is not there for the CleverConversion exception. It’s there to catch any exceptions coming out of printf, and you just happened to be lucky that it caught your exception too.
In the second example, there is no call to printf, so the compiler says, “Well, nothing inside this try block can throw a C++ exception, so I can optimize out the try/catch.” You would also have observed this behavior if there were function calls inside the try block, if the function calls were all to functions that were marked noexcept or if the compiler could prove that they didn’t throw any C++ exceptions (say, because the function is inlined).
This answers the question, but let’s try to look at the whole story.
/EHa./EHa results in less efficient code. We want more efficient code, not less./EHa without any of the costs!It looks like you found some free money on the ground, but is it really free money?
The customer seems to think that the /EHa option results in less efficient code simply because the compiler team is a bunch of jerks and secretly hates you.
No, that’s not why the /EHa option results in less efficient code. The possibility that any memory access or arithmetic operation could trigger an exception significantly impairs optimization opportunities. It means that all variables must be stable at the point memory accesses occur.
Consider the following code fragment:
class Reminder { public: Reminder(char* message) : m_message(message) { } ~Reminder() { std::cout << "don't forget to " << m_message << std::endl; }
void UpdateMessage(char\* message) { m\_message = message; }
private: char* m_message; };
void NonThrowingFunction() noexcept; void DoSomethingElse(); // might throw
void sample_function() { try { Reminder reminder("turn off the lights"); if (NonThrowingFunction()) { reminder.UpdateMessage("feed the cat"); } DoSomethingElse(); } catch (std::exception& e) { Log(e.what()); } }
If compiling without /EHa, the compiler knows that the NonThrowingFunction function cannot throw a C++ exception, so it can delay the store of reminder.``m_message to just before the call to DoSomethingElse. In fact, it is like to do so because it avoids a redundant store.
The pseudo-code for this function might look like this:
allocate 4 bytes in local frame for reminder
l1: call NonThrowingFunction if result is zero load r1 = "turn off the lights" else load r1 = "feed the cat" endif store r1 to reminder.m_message call DoSomethingElse l2: std::cout << "don't forget to " << r1 << std::endl; l3:
clean up local frame
return
if exception occurs between l1 and l2 std::cout << "don't forget to " << reminder.m_message << std::endl; fall through
if exception occurs between l2 and l3 if exception is std::exception Log(e.what()) goto l3 else continue exception search endif
Notice that we optimized out a redundant store by delaying the initialization of reminder, and we enregistered reminder.``m_message in the common code path. Delaying the initialization of reminder is not an optimization available to /EHa because of the possibility that NonThrowingFunction might raise an asynchronous exception that gets converted to a synchronous one:
allocate 4 bytes in local frame for reminder
l0: // cannot delay initialization of reminder load r1 = "turn off the lights" store r1 to reminder.m_message
l1: call NonThrowingFunction if result is nonzero load r1 = "feed the cat" store r1 to reminder.m_message endif call DoSomethingElse l2: std::cout << "don't forget to " << r1 << std::endl; l3:
clean up local frame
return
if exception occurs between l1 and l2 std::cout << "don't forget to " << reminder.m_message << std::endl; fall through
// and there is a new exception region if exception occurs between l0 and l1, or between l2 and l3 if exception is std::exception Log(e.what()) goto l3 else continue exception search endif
The extra code is necessary in order to ensure that the reminder variable is in a stable state before calling NonThrowingFunction. In general, if you turn on /EHa, the compiler must ensure that every object which is accessed outside the try block (either explicitly in code or implicitly via an unwind destructor) is stable in memory before performing any operation that could result in an asynchronous exception, such as accessing memory.
This requirement that variables be stable in memory comes at a high cost, because it not only forces redundant stores to memory, but it also prohibits various types of optimizations based on out-of-order operations.
The CleverConversion is basically a manual replication of what /EHa does, but lying to the compiler and saying, “Um, yeah, don’t worry about asynchronous exceptions.”
Observe what happens if an asynchronous exception occurs inside NonThrowingFunction even though you compiled without the /EHa flag:
We destruct the reminder object, which means printing the m_message to std::``cout. But the non-/EHa version did not ensure that reminder.``m_message was stable. Indeed, if an exception occurs inside NonThrowingFunction, we will try to print reminder.``m_message anyway, even though it is an uninitialized variable.
Printing an uninitialized variable is probably not what the program intended.
So a more complete answer to the scenario is “Yes, it is technically possible to throw a C++ exception from a structured exception handler, but doing so requires that the program be compiled with /EHa in order to avoid undefined behavior.”
And given that avoiding the /EHa flag was the whole purpose of the exercise, the answer to the specific scenario is, “No, this doesn’t work. Your program will behave in undefined ways.”
Category
Topics

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.