两次捕获相同的异常 [英] 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
处遇到了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屋!