user2210021 user2210021 - 29 days ago 14
C# Question

C# More elegant way to check if an exception is within a list of specified exceptions?

I have a need to check if an exception is within a list of specified exceptions and currently my code looks like:

catch (Exception ex) {
if ( (ex is Exception1) || (ex is Exception2) || (ex is Exception3) || (ex is Exception4) || (ex is Exception5) ) {
//do something;
}
}


As you can see the syntax is not very elegant. Is there a better/cleaner way to write this type of expression in C#?

Edit - I was looking for some better build in syntax to treat Exceptions as types so maybe I can build a list of these exceptions and just use something like if a list object includes this ex. Anyway, I think I can bear with the current code for now.

Answer Source
public void test()
{
    try
    {
       // do something something
       return;
    }
    catch (Exception1) {}
    catch (Exception2) {}
    catch (Exception){
       return;
    }

    //do something; 
}

Is not very 'beautiful' but it works.. if any of Exception1 or Exception2 is encountered then //do something will execute. If another exception (represented by the general Exception) is hit then the method will return and it will not do anything (it will not execute //do something).