0
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...");  
    }  
} 
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
  • Output:finally block is always executed Exception in thread main java.lang.ArithmeticException:/ by zero – user2834961 Jan 07 '17 at 09:40
  • It always happens that whether the exception handled or not ,the code after the exception line of code in try block is never executed, why that so?? – user2834961 Jan 07 '17 at 09:43

1 Answers1

0

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

Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49