这个有点抽象,但是有没有办法抛出一个异常,让它进入多个catch block 呢?例如,如果它匹配一个特定的异常,然后是一个非特定的异常。
catch(Arithmetic exception)
{
//do stuff
}
catch(Exception exception)
{
//do stuff
}
最佳答案
拥有多个不同类型的 catch block 是完全可以接受的。但是,行为是第一个候选 block 处理异常。
它不会进入两个 catch block 。与异常类型匹配的第一个 catch block 将处理该特定异常,而不会处理其他异常,即使它在处理程序中重新抛出也是如此。一旦异常进入 catch block ,任何后续的都将被跳过。
为了在两个 block 中捕获异常,您需要像这样嵌套 block :
try
{
try
{
// Do something that throws ArithmeticException
}
catch(ArithmeticException arithException)
{
// This handles the thrown exception....
throw; // Rethrow so the outer handler sees it too
}
}
catch (Exception e)
{
// This gets hit as well, now, since the "inner" block rethrew the exception
}
或者,您可以根据特定的异常类型过滤通用异常处理程序。
关于c# - 我可以执行多个 Catch block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4035477/