0

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

4

7 回答 7

6

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

于 2011-04-04T06:20:51.797 回答
2

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

例如:

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
    }
}
于 2011-04-04T06:27:17.210 回答
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){}
        }

    }
于 2011-04-04T06:24:29.857 回答
1

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

于 2011-04-04T06:20:15.213 回答
1

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

于 2011-04-04T06:21:09.830 回答
1

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

JLS 中的相关部分是14.20.2。那里列出的每个流程都有这样的内容:

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

换句话说,catch与块关联的任何子句都不会尝试finally处理异常。

于 2011-04-04T06:23:57.350 回答
0

执行顺序一般直接用语句的顺序来表示:1.try,2.按指定顺序捕获异常(只执行一次catch),3.finally。

因此,当 finally 块被执行时(请注意,情况总是如此,即使在 try 或 catch 块中抛出 return 语句或异常的情况下)try 语句的执行处于其最后阶段,因此它无法捕获进一步的投掷物。正如已经指出的那样,必须在堆栈下方(或向上,取决于观点;))的位置处理异常。

于 2011-04-04T06:27:59.520 回答