两次捕获相同的异常

St.*_*rio 3 java exception try-catch

我有以下内容:

public void method(){

    try {
        methodThrowingIllegalArgumentException();
        return;
    } catch (IllegalArgumentException e) {
        anotherMethodThrowingIllegalArgumentException();            
        return;
    } catch (IllegalArgumentException eee){ //1
       //do some
       return;
    } catch (SomeAnotherException ee) {
       return;
    }
}
Run Code Online (Sandbox Code Playgroud)

Java不允许我们两次捕获异常,因此我们得到了compile-rime错误//1.但我需要完成我尝试做的事情:

首先尝试该methodThrowingIllegalArgumentException()方法,如果失败IAE,尝试anotherMethodThrowingIllegalArgumentException();,如果失败IAE,请做一些并返回.如果失败而SomeAnotherException只返回.

我怎样才能做到这一点?

Mur*_*nik 6

如果块anotherMethodThrowingIllegalArgumentException()内的调用catch可能会抛出异常,那么它应该被捕获,而不是作为"顶级" try语句的一部分:

public void method(){

    try{
        methodThrowingIllegalArgumentException();
        return;
    catch (IllegalArgumentException e) {
        try {
            anotherMethodThrowingIllegalArgumentException();            
            return;
        } catch(IllegalArgumentException eee){
            //do some
            return;
        }
    } catch (SomeAnotherException ee){
       return;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ St.Antario这对我来说似乎是一种代码味 - 尽管这是正确的答案.如果您必须以这种方式编写代码,您可能可以将其重构为更清晰.据我所知,catch语句不应该做任何可能导致异常情况的事情. (2认同)