catch
是否可以在同一块中捕获多个异常?
try
{ }
catch(XamlException s | ArgumentException a)
{ }
catch
是否可以在同一块中捕获多个异常?
try
{ }
catch(XamlException s | ArgumentException a)
{ }
是的。如果你捕获一个超类,它也会捕获所有子类:
try
{
// Some code
}
catch(Exception e)
{
// ...
}
如果这捕获的数量超出了您的预期,那么您可以通过测试它们的类型来重新抛出您不打算捕获的异常。如果这样做,请小心使用throw;
语法,而不是 throw e;
. 后一种语法破坏了堆栈跟踪信息。
但是您无法使用您建议的语法捕获两种不同的类型。
不像你问的那么简洁。一种方法是捕获所有异常并特别处理这两个:
catch(Exception e)
{
if((e is SystemException) || (e is ArgumentException))
// handle, rethrow, etc.
else
throw;
}
然而,不是 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..... }
}
在 vb.net 中,可以说,检查并决定是否捕获它的任何所需函数Catch Ex As Exception When IsMyException(Ex)
在哪里。在任何内部块运行之前确定是否捕获。不幸的是,C# 的制造者不喜欢允许自定义异常过滤器的想法,可能是因为它会用特定于平台的细节污染语言(大多数平台不支持 .net 样式的异常过滤器)。因此,在 C# 中最好的希望是执行以下操作:IsMyException
Ex
Ex
Finally
无效 HandleThisOrThatException(BaseTypeOfThisThatTheOtherException) { ... } ... // 捕获 ThisException 或 ThatException,但不捕获 TheOtherException 捕捉 (ThisException ex) {HandleThisOrThatException(ex);} 捕捉(ThatException ex){HandleThisOrThatException(ex);}
这是一个不好的例子,因为 anyArgumentException
也是 a SystemException
,所以捕获所有 SystemException
s 也会隐含地得到ArgumentException
s 。