views:

75

answers:

5

I have created custom exception class

public class Web2PDFException : Exception
{


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

in my application I want to find out is throw exception is my custom exception or not.

try
{
}
catch (Exception err)
{
//Find exception type here
}
+1  A: 

either

try
{
}
catch ( Web2PDFException 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 and use is or Type.IsAssignableFrom in Exception Filters

Ruben Bartelink
if( err is Web2PDFException) is that I needed :)
Tomas
To use the "is" operator he does not need to switch to VB.NET
BeowulfOF
@BeowulfOF: I know, but if he's just trying to do filtering based on types - i.e. some sort of conditional catching etc., it may be useful to use an is *in an exception filter rather than a catch block* - it may be an avenue of approach which works. My initial suggestion (and it's still in the answer) is an is in the catch block. Bottom line here is that given that using an `is` is normally a bad smell, we might as well have a laundry list of possible solutions and let Tomas pick what suits him best in his specific context. But yes, it's unlikely.
Ruben Bartelink
+5  A: 
try
{
    // Some code
}
catch (Web2PDFException ex)
{
    // It's your special exception
}
catch (Exception ex)
{
    // Any other exception here
}
batwad
A: 

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
    }
}
Maximilian Mayerl
A: 
try
{
}
catch (Exception err)
{
    if (err is Web2PDFException)
        DoWhatever();
}

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

erikkallen
A: 

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

fealin