I have a C++ DLL with code like this:
LogMessage( "Hello world" );
try {
throw new int;
} catch( int* e ) {
LogMessage( "Caught exception" );
delete e;
}
LogMessage( "Done" );
This DLL is loaded by some third-party application and the code above is invoked. The problem is only the first LogMessage is invoked – even though there’s an exception handler the control flow is transferred to the unknown.
I see this and can’t decide whether it’s some obscure bug to be investigated or just the evil force of the consumer application.
Is it really possible for a consumer application to override the C++ exception handling in a DLL?
EDIT: The problem resolved after thinking on all things to check outlined in the answers. In real code it’s not just throw, there’a a special function for throwing exceptions that has a call to MessageBoxW() Win32 call in debug version. And the consumer application had troubles showing the message box (it’s an NT service) and effectively hung up. So it’s not a problem of C++ exceptions handling in any way.
The code looks OK to me, but I’d be tempted to put a few more catch clauses in to see if it’s hitting one of the other ones. Namely, I’d put in:
catch (const std::exception &ex) { ... log exception ... } catch (...) { ... log exception .. }I would expect that it’ll either hit the pointer catch (even if that’s really not a good idea, see the link that Igor Oks provided) or the std::exception in case it can’t allocated the memory. That said, it should hit one of the three catch clauses so there is no way for the exception to escape the DLL.
I’d also change the object thrown to a value type (even if it is int) and update the catch clause accordingly to see if you get changed behaviour that way.