views:

318

answers:

4

There has already been a question posted here which is very similar. Mine is extending that question a bit more. Say you want to catch multiple types of exception but want to handle it the same way, is there a way to do something like switch case ?

switch (case)
{
  case 1:
  case 2:

  DoSomething();
  break;
  case 3:
  DoSomethingElse()
  break;

}

Is it possible to handle few exceptions the same way . Something like

try
{
}
catch (CustomException ce)
catch (AnotherCustomException ce)
{
  //basically do the same thing for these 2 kinds of exception
  LogException();
}
catch (SomeOtherException ex)
{
 //Do Something else
}
+7  A: 

Currently there is no language construct to accomplish what you want. Unless the exception all derive from a base exception you need to consider refactoring the common logic to a method and call it from the different exception handlers.

Alternatively you could do as explained in this question:

Catch multiple Exceptions at once?

Personally I tend to prefer the method-based approach.

João Angelo
+6  A: 

You should really have a BaseCustomException and catch that.

pdr
A: 

You shouldn't be catching this many custom exceptions,however if you want you can create a common BaseException and catch that.

Stan R.
A: 

I've never actually done this or anything like it, and I don't have access to a compiler for testing purposes but surely something like this would work. Not sure how to actually do the type comparison or if C# would let you replace the if statements with a case statement.

try 
{ 
}
catch (System.Object obj)
{
  Type type;

  type = obj.GetType() ;
  if (type == CustomException || type == AnotherCustomException)
  { 
    //basically do the same thing for these 2 kinds of exception 
    LogException(); 
  } 
  else if  (type == SomeOtherException ex) 
  { 
    //Do Something else 
  }
  else
  {
    // Wasn't an exception to handle here
    throw obj;
  }
}
torak
This might work, but this is not a good solution, since it ignores two very fundamental facts: a) there is a base system Exception class, and you don't need to go all the way down to System.Object; and b) multiple catch statements for different exception classes exist for this very purpose.
Alison R.
I agree with Allison R on point (a), but in relation to point (b) it seems like criticism for answering the question that was asked.
torak
@torak Breaking out common functionality into a method and calling it in various `catch()` blocks is the more elegant way to go, since it doesn't require type checking, and makes proper use of native language constructs for exception handling.
Alison R.
@Allison Excellent point, thanks for the clarification.
torak