【发布时间】:2011-05-01 01:41:28
【问题描述】:
我无法理解异常应该如何传播。我的代码(与下面的通用代码非常相似)执行otherCode() 并在doSomething() 引发异常时失败continue outer。我需要循环解析一堆文件,其中一些文件可能格式不正确(导致异常),然后循环解析数据,这也可能导致异常(例如文件格式正确但缺少字段) .当这些异常发生时,循环应该在其余的字段/文件上继续。
我的困惑/不确定性由以下 cmets 中的问题表示(由?)。
...
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?
}
}
}
我也不理解通过嵌套调用传播,例如如果doSomething() 调用nextMethod(),而nextMethod() 又调用nextNextMethod() 并且其中任何一个抛出异常,什么时候在这些方法中执行捕获与在doSomething() 周围的try-catch 块中执行捕获?例如,如果这些方法throw new,包含try-catch 或没有处理...
【问题讨论】:
-
你确定你捕捉到了正确的异常类型吗?
-
根据printStackTrace(),是的。
标签: java exception-handling try-catch while-loop continue