Catch the same exception twice

情到浓时终转凉″ 提交于 2020-01-04 02:22:46

问题


I have the following:

public void method(){

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

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:

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.

How can I do that?


回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/31611982/catch-the-same-exception-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!