简体   繁体   中英

Exception Handling flow discrepancy

My code is below :-

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

Output is :-

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

As per my knowledge the flow has to be first try then catch and finally at last but as per the output the flow is try then few lines of catch upto the throw exception statement and then finally and the throw exception statement of catch block at last.

Why is there discrepancy in flow, I mean why finally was executed before the throw new exception statement of catch block

Because a block of finally , by definition, has to be executed no matter the outcome of the try or catch clauses.

In your case, the run-time knows there is an exception that has to be propagated upwards, but before doing so, it executes whatever is inside the finally block.

When the finally block is finished, it propagates any exception that might have been raised, or the flow continues otherwise.

You can take a look at the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM