2

catch是否可以在同一块中捕获多个异常?

try
{   }
catch(XamlException s | ArgumentException a)
{   }
4

5 回答 5

7

是的。如果你捕获一个超类,它也会捕获所有子类:

try
{
    // Some code
}
catch(Exception e)
{
    // ...
}

如果这捕获的数量超出了您的预期,那么您可以通过测试它们的类型来重新抛出您不打算捕获的异常。如果这样做,请小心使用throw;语法,而不是 throw e;. 后一种语法破坏了堆栈跟踪信息。

但是您无法使用您建议的语法捕获两种不同的类型。

于 2012-06-26T16:15:22.093 回答
3

不像你问的那么简洁。一种方法是捕获所有异常并特别处理这两个:

catch(Exception e)
{   
  if((e is SystemException) || (e is ArgumentException))
     // handle, rethrow, etc.
  else
     throw;
}
于 2012-06-26T16:16:51.347 回答
2

然而,不是 C# 大师,这在任何 oop 语言中都是标准的。

    try
    {
        string s = null;
        ProcessString(s);
    }
    // Most specific:
    catch (InvalidCastException e) { out_one(e); }
    catch (ArgumentNullException e) { out_two(e); }

    // Least specific - anything will get caught
    // here as all exceptions derive from this superclass
    catch (Exception e)
    {
        // performance-wise, this would be better off positioned as
        // a catch block of its own, calling a function (not forking an if)
        if((e is SystemException) { out_two(); }
        else { System..... }
    }
于 2012-06-26T16:30:12.897 回答
1

在 vb.net 中,可以说,检查并决定是否捕获它的任何所需函数Catch Ex As Exception When IsMyException(Ex)在哪里。任何内部块运行之前确定是否捕获。不幸的是,C# 的制造者不喜欢允许自定义异常过滤器的想法,可能是因为它会用特定于平台的细节污染语言(大多数平台不支持 .net 样式的异常过滤器)。因此,在 C# 中最好的希望是执行以下操作:IsMyExceptionExExFinally

无效 HandleThisOrThatException(BaseTypeOfThisThatTheOtherException)
{ ... }

...
// 捕获 ThisException 或 ThatException,但不捕获 TheOtherException
  捕捉 (ThisException ex) {HandleThisOrThatException(ex);}
  捕捉(ThatException ex){HandleThisOrThatException(ex);}
于 2012-06-26T18:56:26.117 回答
0

这是一个不好的例子,因为 anyArgumentException也是 a SystemException,所以捕获所有 SystemExceptions 也会隐含地得到ArgumentExceptions 。

于 2012-06-26T16:18:41.830 回答