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

问题描述

  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(异常i){
throw new MyExc2();
}
finally {
System.out.print(2);
throw new MyExc1();
}
}

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

我被要求给它输出。我回答 13线程主要MyExc2 中的异常,但正确的答案是 132线程主要MyExc1 中的异常。为什么呢我只是不明白MyExc2在哪里去。

解决方案

根据阅读你的答案,看看你可能想出来我相信你认为在进行中的例外具有优先。请记住:



当一个新的异常抛出在将被传播到该块的一个 catch块或最终块之后,那么当新异常向外传播时,当前异常将被中止(并被遗忘)。新异常开始像任何其他异常一样展开堆栈,从中止当前块(catch或finally块),并受到任何适用的catch或最终块的阻止。



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



当引发新的异常时一个catch块,新的异常仍然受到该catch的finally块,如果有的话。



现在回溯执行记住,每当你击中code> throw ,您应该中止跟踪当前的异常并开始跟踪新的异常。


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();
        }
    }
}

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:

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.

Note that applicable catch or finally blocks includes:

When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.

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子句中抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 18:38