我无法理解异常应该如何传播。我的代码(与下面的通用代码非常相似)执行otherCode()
并在引发异常continue outer
时失败。doSomething()
我需要循环解析一堆文件,其中一些文件可能格式不正确(导致异常),然后循环解析数据,这也可能导致异常(例如文件格式正确但缺少字段) . 当这些异常发生时,循环应该在其余的字段/文件上继续。
我的困惑/不确定性由以下评论中的问题(由?)表示。
...
public static void main(string[] args) {
outer: while ( thingsToDo ) {
try{
someItrType someIterable = doSomething(); // might throw
otherCode(); // only do this if nothing was thrown above?
} catch (SomeExceptionType e) {
handleSomeExceptionType();
continue outer; // keep trying the rest of the loop?
}
otherOtherCode(): // only if nothing thrown, because of the continue?
inner: while( someIterable.next() ) {
try{
doSomethingElse(); // might throw
} catch (SomeExceptionType e) {
handleSomeExceptionType();
continue inner; // keep trying the inner loop?
}
doThisIfAllOkay(); // only if no exceptions thrown?
}
}
}
我也不明白通过嵌套调用进行传播,例如 ifdoSomething()
调用nextMethod()
,它依次调用nextNextMethod()
并且其中任何一个抛出异常,什么时候在这些方法中执行捕获,而不是在 try-catch 块中doSomething()
?例如,如果这些方法throw new
包含 try-catch 或没有处理...