-2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Jason
  • 821
  • 2
  • 16
  • 28
  • Define "elegant"? There's not a built-in syntax to do that. Only other way I can think of is a list of types and a loop or Linq query, which is _less_ elegant in my opinion. – D Stanley Apr 09 '15 at 14:31
  • 2
    You should have a clean inheritance model of all these exceptions and then catch just the right parent of all exceptions of interest. – DrKoch Apr 09 '15 at 14:31
  • 2
    Check this question; http://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once – horHAY Apr 09 '15 at 14:32
  • Are we barking up the wrong tree here? I mean, why do you need to distinguish all these exceptions? Usually, if you really need, you just log the exception information and take safe measures to exit the code path. I hope that you are not driving your code flow using exceptions. – Steve Apr 09 '15 at 14:38
  • Related: how to check an object's type against a list of types: http://stackoverflow.com/q/20333634/945456 – Jeff B Oct 05 '16 at 13:41

2 Answers2

1
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).

tupini07
  • 518
  • 5
  • 13
0

I think that you should not make this solution. It's better to catch each exception in a block, as follow:

catch (Exception1 ex) {
}
catch (Exception2 ex) {
}