试着抓。以相同的方式处理多个异常(或通过降低)

时间:2010-02-18 19:05:22

标签: c# exception exception-handling error-handling

已发布here的问题非常相似。我正在扩大这个问题。假设你想要捕获多种类型的异常,但想以同样的方式处理它,有没有办法做一些像switch case这样的事情?

switch (case)
{
  case 1:
  case 2:

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

}

是否可以以相同的方式处理少数异常。像

这样的东西
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
}

6 个答案:

答案 0 :(得分:15)

目前没有语言结构可以完成你想要的任务。除非异常都来自基本异常,否则您需要考虑将公共逻辑重构为方法并从不同的异常处理程序中调用它。

或者您可以按照此问题中的说明进行操作:

Catch multiple Exceptions at once?

我个人倾向于选择基于方法的方法。

答案 1 :(得分:7)

你应该有一个BaseCustomException并抓住它。

答案 2 :(得分:4)

这是copied from another posting,但我将代码拉到此主题:

抓住System.Exception并启用类型

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

    throw;
}

我更喜欢这个在几个catch块中重复一个方法调用。

答案 3 :(得分:1)

在vb.net中,可以使用异常过滤器来表示,例如

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

不幸的是,无论出于何种原因,C#的实现者都拒绝允许在C#中编写异常过滤代码。

答案 4 :(得分:0)

您不应该捕获这么多自定义异常,但是如果您愿意,可以创建一个公共BaseException并抓住它。

答案 5 :(得分:-5)

我从来没有真正做过这样或类似的事情,而且我无法访问编译器以进行测试,但是这样的事情肯定会起作用。不确定如何实际进行类型比较,或者C#是否允许用case语句替换if语句。

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