执行多个catch块 [英] executing multiple catch blocks

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

问题描述

这是一个有点抽象,但有抛出一个异常,并将它输入多个catch块任何可能的方式。也就是说,如果它匹配特定异常随后的非特异性的。

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

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

我并不真的需要做到这一点我只需要这个我只是想知道,如果它是可能的。

I don't really NEED to do this I just need to this I just am wondering if it is possible.

推荐答案

这是完全可以接受的differring类型的多个catch块。然而,该行为是第一候选块处理该异常。

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天全站免登陆