在finally和catch块中抛出异常

3

在 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 (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) {
            System.out.print(3);
        }
        finally {
            System.out.print(4);
            throw new Exception();
        }
    }

}

我尝试多次执行上述代码,每次都会得到不同的输出结果。

output 1: 1Exception in thread "main" 342test.MyExc1
at test.C1.main(C1.java:18)
output 2: 1342Exception in thread "main" test.MyExc1
at test.C1.main(C1.java:18)
output 3: 1Exception in thread "main" test.MyExc1
342 at test.C1.main(C1.java:18)
output4:  1Exception in thread "main" 34test.MyExc1
2 at test.C1.main(C1.java:18)

请解释。
1个回答

11
你所看到的只是在向System.outSystem.err写入内容之间的竞争条件。你明确地使用System.out.print打印了1、3、4、2,异常被抛出并自动转储到System.err中。因此,每个输出都是"1342",而异常堆栈跟踪信息则在某个位置。
实际的执行流程在所有情况下都是相同的,只有输出不同。为了证明这一点,你可以将整个主方法包装在一个try/catch块中,并将异常写入System.out,这样它就会与所有现有的System.out调用同步,也不会产生竞争条件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接