我可以执行多个Catch块吗? [英] Can I execute multiple Catch blocks?

查看:597
本文介绍了我可以执行多个Catch块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有点抽象,但是是否有引发异常并使其进入多个catch块的可能方法?例如,如果它匹配特定的例外,然后匹配非特定的例外。

This is a bit abstract, but is there any possible way to throw an exception and have it enter multiple catch blocks? For example, if it matches a specific exception followed by a non-specific exception.

catch(Arithmetic exception)
{
  //do stuff
}
catch(Exception exception)
{
  //do stuff
}


推荐答案

具有多个不同类型的捕获块是完全可以接受的。但是,其行为是第一个候选块会处理该异常。

It is perfectly acceptable to have multiple catch blocks of differring types. However, the behavior is that the first candidate block handles the exception.

它不会同时进入两个catch块。与异常类型匹配的第一个catch块将处理该特定异常,而不会处理其他异常,即使该异常已在处理程序中重新抛出也是如此。一旦异常进入catch块,所有随后的异常都将被跳过。

It will not enter BOTH catch blocks. The first catch block that matches the exception type will handle that specific exception, and no others, even if it's rethrown in the handler. Any subsequent ones will be skipped once an exception enters a catch block.

为了将异常捕获到两个块中,您需要像这样嵌套两个块:

In order to have an exception caught in BOTH blocks, you would need to either nest blocks like so:

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
}

或者,您可以过滤通用异常处理程序基于异常的特定类型。

Alternatively, you could filter in a generic exception handler based on the specific type of exception.

这篇关于我可以执行多个Catch块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆