Exception thrown in catch and finally clause

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, the current exception is aborted (and forgotten) and the new exception is thrown. 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块中产生新异常, 当前的异常失效并被丢弃,新异常会被后续的catch和finally块处理。

注意: 一个新异常在catch块产生时,会被这个catch匹配的finally处理。

public class A {

    public static void main(String[] args) {
        try{
            exceptionFunction();
            
        }catch(Exception e){
            
            // print catches which Exception 111, 222, or 333.
            System.out.println(e.getMessage());
        }
    }

    public static void exceptionFunction(){
        try{
            throw new IllegalArgumentException("111");
        }catch(Exception e){
            throw new IllegalArgumentException("222");
        }finally{
            throw new IllegalArgumentException("333");
        }
    }
}

above code will print:

333

原文地址:https://www.cnblogs.com/lpthread/p/3482899.html