Java:关于finally块的假设性问题

时间:2011-04-04 06:18:15

标签: java error-handling try-catch-finally

如果在finally块中抛出错误会发生什么?它是否在一个相应的catch子句中处理?

7 个答案:

答案 0 :(得分:6)

仅当您在finally块中放入另一个try-catch块时。否则就像其他任何错误一样。

答案 1 :(得分:2)

处理异常,直到最终阻止它为止。

public static void main(String[] args) throws Exception {
        try {
            System.out.println("In try");
        } catch (Exception e) {
            System.out.println("In catch");
        } finally{
            throw new Exception();
        }

    }

上面的代码会抛出异常,但如果按照以下方式执行,它将起作用:

public static void main(String[] args){
        try {
            System.out.println("In try");
        } catch (Exception e) {
            System.out.println("In catch");
        } finally{
             try{
                     throw new Exception();
                 }catch(Exception e){}
        }

    }

答案 2 :(得分:2)

您需要在finally或catch块中包含try-catch块。

e.g:

try {
    // your code here
} finally {
    try {
        // if the code in finally can throw another exception, you need to catch it inside it
    } catch (Exception e) {
       // probably not much to do besides telling why it failed
    }
} catch (Exception e) {
    try {
        // your error handling routine here
    } catch (Exception e) {
       // probably not much to do besides telling why it failed
    }
}

答案 3 :(得分:1)

不。它会被一个catch捕获,然后整个try / catch / finally嵌套在另一个try / catch中。否则该异常将被抛出函数,并由函数的调用者处理。

答案 4 :(得分:1)

不,不。您必须在finally块中处理它或在方法描述中定义正确的throw声明。

答案 5 :(得分:1)

不,catch块只能捕获在相应的try块中抛出的异常 - 而不是finally块。 (当然,如果finally块在另一个try块内,则仍然会使用 try块的catch子句。)

JLS中的相关部分是14.20.2。其中列出的每个流程都有类似的内容:

  

如果finally块因任何原因突然完成,那么try语句会因同样的原因而突然完成。

换句话说,没有尝试与catch块关联的任何finally子句来处理异常。

答案 6 :(得分:0)

执行顺序通常由语句顺序直接指示:1。尝试,2。按指定的顺序捕获异常(只执行一次捕获),3。最后。

所以当finally块被执行时(请注意,总是这样,即使在try语句或catch块中抛出return语句或异常的情况下),try语句的执行也处于最后阶段,因此它无法捕获更多的扔石头。正如已经指出的那样,异常必须在堆栈中的某个位置处理(或者向上,取决于视点;)。)