问题
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