两次捕获相同的异常
Catch the same exception twice
我有以下内容:
public void method(){
try {
methodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException e) {
anotherMethodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException eee){ //1
//do some
return;
} catch (SomeAnotherException ee) {
return;
}
}
Java 不允许我们两次捕获异常,因此我们在 //1
处遇到了编译错误。但我需要做我想做的事:
先尝试 methodThrowingIllegalArgumentException()
方法,如果失败 IAE
,尝试 anotherMethodThrowingIllegalArgumentException();
,如果 IAE
也失败,再尝试 return.如果失败 SomeAnotherException
只是 return.
我该怎么做?
如果 catch
块中的 anotherMethodThrowingIllegalArgumentException()
调用可能会抛出异常,则应该在那里捕获它,而不是作为 "top level" try
语句的一部分:
public void method(){
try{
methodThrowingIllegalArgumentException();
return;
catch (IllegalArgumentException e) {
try {
anotherMethodThrowingIllegalArgumentException();
return;
} catch(IllegalArgumentException eee){
//do some
return;
}
} catch (SomeAnotherException ee){
return;
}
}
我有以下内容:
public void method(){
try {
methodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException e) {
anotherMethodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException eee){ //1
//do some
return;
} catch (SomeAnotherException ee) {
return;
}
}
Java 不允许我们两次捕获异常,因此我们在 //1
处遇到了编译错误。但我需要做我想做的事:
先尝试 methodThrowingIllegalArgumentException()
方法,如果失败 IAE
,尝试 anotherMethodThrowingIllegalArgumentException();
,如果 IAE
也失败,再尝试 return.如果失败 SomeAnotherException
只是 return.
我该怎么做?
如果 catch
块中的 anotherMethodThrowingIllegalArgumentException()
调用可能会抛出异常,则应该在那里捕获它,而不是作为 "top level" try
语句的一部分:
public void method(){
try{
methodThrowingIllegalArgumentException();
return;
catch (IllegalArgumentException e) {
try {
anotherMethodThrowingIllegalArgumentException();
return;
} catch(IllegalArgumentException eee){
//do some
return;
}
} catch (SomeAnotherException ee){
return;
}
}