Java Finally block



In the previous chapter we have studied the nested try and catch blocks in this chapter we will be learning the finally block.

Finally block : Exception Handling in Java

  1. Finally Block in always executed irrespective of exception is handled or not
  2. Finally is not a function, It is keyword in java
  3. Finally performs the functions such as closing the stream or file and closing connections.
  4. Finally always gets executed before terminating the program by JVM.
  5. Finally should be after try and catch and is optional
  6. Each try block has minimum 0 and maximum 1 finally block.

Flowchart for Finally Statement –

finally-block-in-java

Finally block : Syntax

try {
-------
-------
} catch(Exception e) {
-------
-------
}
finally {

}

Tip 1 : Finally block is optional

In the program we can have minimum zero and maximum one finally statement.

public class MyExceptionExample {
    public static void main(String[] a){
        
        try{
            int i = 10/0;
        } catch(Exception ex){
            System.out.println("Inside 1st catch Block");
        }
        

        try{
            int i = 10/10;
        } catch(Exception ex){
            System.out.println("Inside 2nd catch Block");
        } finally {
            System.out.println("Inside 2nd finally block");
        }
    }
}

In the 1st try statement block we can see that we don’t have finally block but in the 2nd try block we have finally block. So finally block is always optional.

finally {
    System.out.println("Inside 2nd finally block");
}

2nd try block does not throw any exception but still after the execution of try block code executes finally statement block

Output :

Inside 1st catch Block
Inside 2nd finally block

Tip 2 : Finally block is not executed in below two cases

  1. If following statement is included in the try block (Terminating code using system exit)
  2. System.exit(0);
    
  3. If the thread executing the try or catch code is interrupted or killed, the finally statement block may not execute [For more info]