希望我能清楚地解释这一点。如果我有一个包含许多步骤的主要方法,这些步骤可能会产生不同的异常,有些是致命的,有些不是,我是否必须分别捕获“可恢复”的异常?看起来这可能会导致大量的 try/catch 块,如下所示:
public static void main (String[] args) {
try {
//...
for (int i=0;someArray.length;i++) {
try{
System.out.println("I = " + i);
doSometing(i);
} catch (RecoverableException e) {
//recover, continue, whatever
//log warning
//keep
}
}//end for loop
try {
doSomethingElse();
} catch (AnotherRecoverableException e) {
//not fatal, keep on chugging
}
//...
//do more stuff that can throw unrecoverable exceptions
} catch (UnrecoverableException e) {
System.out.println("I can't handle this, it's too much!");
e.printStackTrace();
}
}
有一个更好的方法吗?