class TestFinallyBlock1{  
    public static void main(String args[]){  
        try{  
            int data=25/0;  
            System.out.println(data);  
        }  
        catch(NullPointerException e){System.out.println(e);}  
        finally{System.out.println("finally block is always executed");}  
        System.out.println("rest of the code...");  
    }  
} 
1

There are 1 answers

0
Kohei TAMURA On

I think you can understand the behaviour if you extract method and add the additional try-catch block as follows:

public class TestFinallyBlock1 {
    public static void main(String args[]) {
        try {
            throwArithmeticException();
            System.out.println("rest of the code...");
        } catch (ArithmeticException e) {
            System.out.println(e);
        }
    }

    private static void throwArithmeticException() {
        try {
            int data = 25 / 0;
            System.out.println(data);
        } catch (NullPointerException e) {
            System.out.println(e);
        } finally {
            System.out.println("finally block is always executed");
        }
    }
}

For more details, please refer to Java Language Specification - Execution of try-finally and try-catch-finally