Identifying Exception Type in a handler Catch Block

UPDATED: assuming C# 6, the chances are that your case can be expressed as an exception filter. This is the ideal approach from a performance perspective assuming your requirement can be expressed in terms of it, e.g.:

try
{
}
catch ( Web2PDFException ex ) when ( ex.Code == 52 )
{
}

Assuming C# < 6, the most efficient is to catch a specific Exception type and do handling based on that. Any catch-all handling can be done separately

try
{
}
catch ( Web2PDFException ex )
{
}

or

try
{
}
catch ( Web2PDFException ex )
{
}
catch ( Exception ex )
{
}

or (if you need to write a general handler - which is generally a bad idea, but if you're sure it's best for you, you're sure):

 if( err is Web2PDFException)
 {
 }

or (in certain cases if you need to do some more complex type hierarchy stuff that cant be expressed with is)

 if( err.GetType().IsAssignableFrom(typeof(Web2PDFException)))
 {
 }

or switch to VB.NET or F# and use is or Type.IsAssignableFrom in Exception Filters


When dealing with situations where I don't exactly know what type of exception might come out of a method, a little "trick" I like to do is to recover the Exception's class name and add it to the error log so there is more information.

try
{
   <code>

} catch ( Exception caughtEx )
{
   throw new Exception("Unknown Exception Thrown: "
                       + "\n  Type:    " + caughtEx.GetType().Name
                       + "\n  Message: " + caughtEx.Message);
}

I do vouch for always handling Exceptions types individually, but the extra bit of info can be helpful, specially when dealing with code from people who love to capture catch-all generic types.


try
{
    // Some code
}
catch (Web2PDFException ex)
{
    // It's your special exception
}
catch (Exception ex)
{
    // Any other exception here
}

💡 Alternative Solution 💡

Instead of halting a debug session, just to add some throw-away statements into the code to then recompile/restart.... why not just use the debugger to answer that question immediately when a breakpoint is hit?

How?

Through the use of the Visual Studio's debug Immediate Window one can type in the call to GetType() after the breakpoint is hit. Then once Enter is pressed, the type is provided on the next line.

The immediate window also allows one to interrogate other variables and classes/structures as needed in that scope.

See VS Docs: Immediate Window


For example I needed to divine what exception I was getting and then just extracted the Name property of GetType to give me that info. All without having to recompile.

enter image description here


Special Variable $exception

There is also the special variable $exception which can be used in the Immediate window. Typing that in will evaluate the currently caught exception and write out the reflected information of that exception.

Tags:

C#

Exception