Identifying Exception Type in a handler Catch Block

C#Exception

C# Problem Overview


I have created custom exception class

public class Web2PDFException : Exception
{
    public Web2PDFException(string message, Exception innerException)
        : base(message, innerException) { ... }
}

In my application how can I find out if it is my custom exception or not?

try {  ...  }

catch (Exception err)
{
//Find exception type here
}

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
        DoWhatever();
}

but there is probably a better way of doing whatever it is you want.

Solution 6 - C#

You should always catch exceptions as concrete as possible, so you should use

try
{
    //code
}
catch (Web2PDFException ex)
{
    //Handle the exception here
}

You chould of course use something like this if you insist:

try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
    {
        //Code
    }
}

Solution 7 - C#

you can add some extra information to your exception in your class and then when you catch the exception you can control your custom information to identify your exception

this.Data["mykey"]="keyvalue"; //you can add any type of data if you want 

and then you can get your value

string mystr = (string) err.Data["mykey"];

like that for more information: http://msdn.microsoft.com/en-us/library/system.exception.data.aspx

Solution 8 - C#

Alternatively:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomasView Question on Stackoverflow
Solution 1 - C#OskuroView Answer on Stackoverflow
Solution 2 - C#Ruben BartelinkView Answer on Stackoverflow
Solution 3 - C#ΩmegaManView Answer on Stackoverflow
Solution 4 - C#batwadView Answer on Stackoverflow
Solution 5 - C#erikkallenView Answer on Stackoverflow
Solution 6 - C#Maximilian MayerlView Answer on Stackoverflow
Solution 7 - C#fealinView Answer on Stackoverflow
Solution 8 - C#Joe BView Answer on Stackoverflow