c# - 我可以执行多个 Catch block 吗?

标签 c# exception-handling try-catch

这个有点抽象,但是有没有办法抛出一个异常,让它进入多个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/

相关文章:

c# - Angular 如何在 WebApi asp.net mvc 中工作

C# - Xamarin 表单在切换时删除 ListView 项

java - 如何通过在 Try-Catch While 循环中输入特定字母来退出程序?

Powershell:使用 try and catch 进行错误处理

c# - Base-64 字符串中的无效字符

c# - C#Finisar SQLite日期时间比较问题

.net - 由于动态组装,Assembly.GetManifestResourceNames() 异常

java - catch block 直接父类和子类处理异常有什么区别

java - @ControllerAdvice 异常处理程序方法未被调用

azure - Invoke-AzVMRunCommand - 错误处理的最佳实践?