2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Finally block in java

Lets pass through an examples:

public class ExceptionExample1 {
    public static void main(String[] args){
        System.out.println(callMethod());
    }
    
    static boolean callMethod(){
        try{
            return true;
        } finally {
            return false;
        }
    }
}


Basically people might think like it will return true and the result will print as true.
But this is not entirely true fact. In try-finally block the finally block must executes once control goes from try block.
The base true fact is the try block executes normally or abnormally, finally block will execute.

If System.exist(0);, we execute in try block will be an exceptional case.

But, here the whole try-finally block will execute abruptly, which results the output as false.

In summary, every finally block should complete normally, barring as unchecked exception. Never exit a finally block with a return, break, continue or throw and never allow a checked exception to propagate out of a finally block.