两次捕获相同的异常 [英] Catch the same exception twice

查看:78
本文介绍了两次捕获相同的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

public void method(){

    try {
        methodThrowingIllegalArgumentException();
        return;
    } catch (IllegalArgumentException e) {
        anotherMethodThrowingIllegalArgumentException();            
        return;
    } catch (IllegalArgumentException eee){ //1
       //do some
       return;
    } catch (SomeAnotherException ee) {
       return;
    }
}

Java不允许我们两次捕获该异常,因此我们在//1处遇到了compile-rime错误.但是我需要做我想做的事情:

Java does not allow us to catch the exception twice, so we got compile-rime error at //1. But I need to do exactly what I try to do:

首先尝试methodThrowingIllegalArgumentException()方法,如果因IAE而失败,请尝试anotherMethodThrowingIllegalArgumentException();,如果也因IAE而失败,则执行一些操作并返回.如果失败并显示SomeAnotherException,请返回.

try the methodThrowingIllegalArgumentException() method first and if it fails with IAE, try anotherMethodThrowingIllegalArgumentException();, if it fails with IAE too, do some and return. If it fails with SomeAnotherException just return.

我该怎么办?

推荐答案

如果catch块内的anotherMethodThrowingIllegalArgumentException()调用可能引发异常,则应在此处捕获该异常,而不应将其作为顶级" 声明:

If the anotherMethodThrowingIllegalArgumentException() call inside the catch block may throw an exception it should be caught there, not as part of the "top level" try statement:

public void method(){

    try{
        methodThrowingIllegalArgumentException();
        return;
    catch (IllegalArgumentException e) {
        try {
            anotherMethodThrowingIllegalArgumentException();            
            return;
        } catch(IllegalArgumentException eee){
            //do some
            return;
        }
    } catch (SomeAnotherException ee){
       return;
    }
}

这篇关于两次捕获相同的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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