pnmhtkr
pnmhtkr

Reputation: 53

Java not printing messages after `finally` block

This question relates to the finally blocks in Java. Here "rest of the code" is not printing, which is after the finally block.

But when an exception is not there then it will print whatever is after the finally block.

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

Upvotes: 0

Views: 607

Answers (1)

Prabhav
Prabhav

Reputation: 457

Because you was not catching java.lang.ArithmeticException and code gets terminated at that point.

Try this:

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

Upvotes: 5

Related Questions