开发者

try- catch. Handling multiple exceptions the same way (or with a fall through)

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
}


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.


You should really have a BaseCustomException and catch that.


This is copied from another posting, but I am pulling the code to this thread:

Catch System.Exception and switch on the types

catch (Exception ex)            
{                
    if (ex is FormatException || ex is OverflowException)
    {
        WebId = Guid.Empty;
        return;
    }

    throw;
}

I prefer this to repeating a method call in several catch blocks.


In vb.net, one can use exception filters to say, e.g.

  Catch Ex As Exception When TypeOf Ex is ThisException Or TypeOf Ex is ThatException

Unfortunately, for whatever reasons, the implementors of C# have as yet refused to allow exception filtering code to be written within C#.


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


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;
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜