在 catch 和 finally 子句中抛出异常 [英] Exception thrown in catch and finally clause

查看:39
本文介绍了在 catch 和 finally 子句中抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于大学的 Java 问题,有这样一段代码:

On a question for Java at the university, there was this snippet of code:

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}

public class C1 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.print(1);
            q();
        }
        catch (Exception i) {
            throw new MyExc2();
        }
        finally {
            System.out.print(2);
            throw new MyExc1();
        }
    }

    static void q() throws Exception {
        try {
            throw new MyExc1();
        }
        catch (Exception y) {
        }
        finally {
            System.out.print(3);
            throw new Exception();
        }
    }
}

我被要求提供它的输出.我回答了线程主 MyExc2 中的 13Exception,但正确的答案是线程主 MyExc1 中的 132Exception.为什么会这样?我就是不明白 MyExc2 去哪里了.

I was asked to give its output. I answered 13Exception in thread main MyExc2, but the correct answer is 132Exception in thread main MyExc1. Why is it that? I just can't understand where does MyExc2 go.

推荐答案

根据阅读您的答案并了解您想出它的可能性,我相信您认为进行中的异常"具有优先级".请记住:

Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:

当在 catch 块或 finally 块 中抛出新异常并将传播到该块之外时,当前异常将被中止(并忘记),因为新异常是向外传播.新异常开始像任何其他异常一样展开堆栈,从当前块(catch 或 finally 块)中止并在此过程中受到任何适用的 catch 或 finally 块的影响.

When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.

请注意,适用的 catch 或 finally 块包括:

在 catch 块中抛出新异常时,新异常仍受该 catch 块的 finally 块(如果有)的约束.

现在回溯执行,记住,每当你点击 throw 时,你应该中止跟踪当前异常并开始跟踪新异常.

Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.

这篇关于在 catch 和 finally 子句中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆