异常处理流程差异

Exception Handling flow discrepancy

我的代码如下:-

class Varr {    
    public static void main(String[] args) {    
        try {
            System.out.println(10/0);
        }
        catch(ArithmeticException e) {
            System.out.println("catch1");
            System.out.println("catch1");
            throw new ArithmeticException ("Exce");             
        }
        finally {   
            System.out.println("finally");
        }
    }
}

输出为:-

catch1

catch1

finally

Exception in thread "main" java.lang.ArithmeticException: Exce
  at one.Varr.main(Varr.java:22)

据我所知,流程必须先尝试,然后捕获,最后是最后,但根据输出,流程是尝试,然后是几行捕获到抛出异常语句,最后是抛出异常语句终于赶上块了。

为什么流程不一致,我的意思是为什么finally在catch块的throw new exception语句之前执行

因为 finally 的块,根据定义,无论 trycatch 子句的结果如何,都必须执行。

在你的例子中,运行-time 知道有一个必须向上传播的异常,但在这样做之前,它会执行 finally 块内的任何内容。

finally 块完成时,它会传播可能已引发的任何异常,否则流程将继续。

你可以看看essentials of finally

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.