Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

Identifying unmanaged exceptions in managed code

I am calling unmanaged C++ code from managed C++ code.

The unmanaged code throws one of any number of unmanaged exceptions (derived from std::exception).  These show up (and so are caught) in the managed code as System::Runtime::InteropServices::SEHException.

There are multiple possible unmanaged exceptions that might give rise to this single managed exception, and the action the managed code takes depends upon which unmanaged exception was thrown.

Once I catch this SEHException, how do I determine what unmanaged exception caused it?  I tried using GetBaseException(), but this is, again, a managed type, not an pointer to the unmanaged exception (I tried using dynamic_cast on the thing to no avail).

Any help you can give me would be appreciated.


Bill Press
Wednesday, February 2, 2005

If you are calling from managed C++ and the exception type is visible to the calling code you should be able to catch the unmanaged exception directly.

We use this pattern frequently:

[managed code]
  ... call unmanaged code ...
catch (MyException* err)
  throw ExceptionBridge::Convert(err);

Where MyException is a class visible to both the managed and unmanaged code, and ExceptionBridge::Convert is a function that looks at the error and converts it into an appropriate managed exception for higher levels to handle.

Rob Walker
Wednesday, February 2, 2005

That would be nice if it were what I'm seeing, but it's not.  My unmanaged code is supposed to throw an unmanaged exception ("ERFException"), but the managed calling routine is getting an SEHException.

When I look up SEHException in MSDN and google, I find that it's an exception created when throwing an unmanaged exception into managed code.

I wonder: are you using a compiler setting that prevents this conversion?  That would be very helpful.

Otherwise, if anybody else has any thoughts, I'd be interested in hearing them.  I'm open to just about anything at this point.

Bill Press
Wednesday, February 2, 2005

Hi Bill,

I've had the same confusion, but worked it out in the end.  Rob was right when he said you can just catch your unmanaged exception, what is confusing is that when in debug mode the exception shows up as an SEHException, however you'll find that if you step through the catch you'l find it behaves as if it were catching the unmanaged exception.  So I suspect the following code will work (ignoring the debugger)

try { unmanaged code...
catch (UnmanagedException & e) {
  throw new ManagedException( e.what() );
  .. or whatever ..

Hope that helps


Ed Kennard
Friday, February 18, 2005

*  Recent Topics

*  Fog Creek Home