non-clr exceptions

J

Jon Paugh

Hi,

How do you catch an exception from unmanaged code?

Will

try
{
// unmanaged code
}
catch (Exception e)
{
}

do?

Or do I need:

try
{
}
catch (Exception e)
{
// for managed exceptions
}
catch
{
// for unmanaged exceptions
}

Which exceptions will go to the first catch block and
which will go to the second?

Jon Paugh
 
E

Eric Gunnerson [MS]

The first block will catch any managed exceptions (ie those derived from
Exception), and the second one will catch any other exceptions, though
there's no way to get to the value that was thrown.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://weblogs.asp.net/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
D

Dave

Typically unmanaged code will throw an exception of type SEHException or
COMException, so if you use

catch(System.Exception ex){}

you will catch both of these since they are both derived from
System.Exception. However, figuring out what the exception means may be
difficult as the mapping from unmanaged exceptions to managed exception
types is not simple or direct, and some exceptions may not roundtrip through
the CLR faithfully.

Using the untyped catch block

catch { ... }

will catch untyped, or non-CLI compliant exceptions. This will catch
exceptions of any type, including untyped exceptions (e.g. numeric values,
such as 0xC0000005). If all your code is managed and CLI-compliant then you
should never get any untyped exceptions as the runtime will translate Win32
exception codes into managed exception types for you. Also, using this form
of a catch block means that you will not have an exception object that you
can programmatically examine.

If you are writing managed code I would not use this - let untyped
exceptions bubble up the callstack. I would instead use

catch(Exception) { ... } // no object - don't care about it

or
catch(Exception ex) {...} ///if you want to use the object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

exceptions 1
Error Hanling in .NET 4
Proper unmanaged to managed exception handling -- SEHException and 3
catch exceptions 2
.NET has a broken Exception model 42
Exception 3
.Net Exceptions 24
Try... Catch performance 6

Top