在一个catch块中捕获多个异常类型 [英] Catching multiple exception types in one catch block

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

问题描述

我想要一个更干净的方式来获取以下功能,在一个块中捕获 AError BError

I'd like a cleaner way to obtain the following functionality, to catch AError and BError in one block:

try
{
    /* something */
}
catch( AError, BError $e )
{
    handler1( $e )
}
catch( Exception $e )
{
    handler2( $e )
}

有什么办法吗?或者我必须分别抓住它们?

Is there any way to do this? Or do I have to catch them separately?

AError Berror 有一个共享的基类,但它们也与其他类型共享,我想通过 handler2 ,所以我不能只是抓住基地

AError and Berror have a shared base class, but they also share it with other types that I'd like to fall through to handler2, so I can't just catch the base class.

推荐答案

如果您可以修改例外情况,使用这个答案

If you can modify the exceptions, use this answer.

如果你不能,你可以尝试用 Exception 然后检查使用 instanceof

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

但是更好地使用上述答案中所述的多个catch块

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}

这篇关于在一个catch块中捕获多个异常类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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