【问题标题】:Exception propagation through nested loops/calls通过嵌套循环/调用进行异常传播
【发布时间】: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


【解决方案1】:

当 try 块中发生异常时,它会立即导致程序流移动到 catch 块。 try 块中发生异常后的任何代码都不会执行。

使用continue 关键字会使循环跳到下一个迭代,从循环的顶部开始,因此catch 块下面的任何代码也不会执行。

就嵌套函数而言:
异常处理有 2 个选项。要么你自己处理它,要么你声明你的函数可以抛出一个异常(那个特定类型的)。假设您程序中的每个函数都声明为throws Exception,那么异常会从您的所有代码中冒出,一直到Java 虚拟机,然后Java 虚拟机将终止。基本上,带有异常的嵌套函数会不断将其向上传递到堆栈中,直到在 try/catch 块中处理。

【讨论】:

  • 除非在 catch 块中明确地重新抛出异常,否则 try-catch 将停止传播?
  • ...或者如果没有遇到适当的 catch 块,程序将终止。 (对于其他出色答案的完整性,+1)
  • @Mark - 你太客气了,@reve 先生 - 是的,try-catch 停止传播,只要 try-catch 指定正确的异常类型
  • 感谢您非常清楚的解释。现在我只需要弄清楚当这个 try-catch 深入到别人库中的一堆方法调用中时该怎么办......
猜你喜欢
  • 2010-10-12
  • 2012-03-02
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多