What is the importance of finally block in exception handling?

Solution:

A finally block will always be executed, whether or not an exception is actually thrown. Even in the case where the catch statement is missing and an exception is thrown, the finally block will still be executed. Last thing to mention is that the finally block is used to release resources like I/O buffers, database connections, etc.

Sample code below shows the finally block when exception is thrown.

Finally Block

public class DivideByZeroException
{  
     public static void main(String []args){  
        try{  
            int a = 1;   
            System.out.println(a/0);  
        }
        catch(Exception exception)
        {
          System.out.println("exception is thrown");
        }
        finally 
        {  
            System.out.println("after the exception is handled");  
        }  
     }  
}
0 answers