可以在同一个catch块中捕获多个异常吗?
try
{ }
catch(XamlException s | ArgumentException a)
{ }发布于 2012-06-27 00:15:22
是。如果你捕获一个超类,它也会捕获所有的子类:
try
{
// Some code
}
catch(Exception e)
{
// ...
}如果这捕获了比您想要的更多的异常,那么您可以通过测试它们的类型来重新抛出您不打算捕获的异常。如果这样做,请注意使用throw;语法,而不是 throw e;。后一种语法阻塞了堆栈跟踪信息。
但是您不能使用您提出的语法来捕获两种不同的类型。
发布于 2012-06-27 00:16:51
并不像你问的那样简洁。一种方法是捕获所有异常并特殊处理这两个异常:
catch(Exception e)
{
if((e is SystemException) || (e is ArgumentException))
// handle, rethrow, etc.
else
throw;
}发布于 2012-06-27 00:30:13
然而,不是没有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..... }
}https://stackoverflow.com/questions/11211548
复制相似问题