Finally block in Java

Java Finally block – Exception handling

Java finally block is a block used to execute important code such as closing the connection, etc.Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.The finally block follows the try-catch block.

Syntax of Finally block:

try {
    //Statements that may cause an exception
}
catch {
   //Handling exception
}
finally {
   //Statements to be executed
},

Example of Finally Block:

public class FinallyBlock{
    public static void main(String[] args) {
        try {
            String s = null;  
                        System.out.println(s.length());  
            
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception ");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception ");
        } catch (Exception e) {
            System.out.println("Parent Exception ");
        } finally {  
            System.out.println("finally block is always executed");  
        } 
        System.out.println("Execution done");

    }
}

When you run this program, it will output:

Parent Exception

finally block is already executed

Execution done

When an exception occur but not handled by the catch block Example:

public class Finally Block{
    public static void main(String[] args) {
        try {
            System.out.println("hello" + " " + 1/0);
            
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBounds Exception ");
        }
        finally {  
            System.out.println("finally block is always executed");  
            } 
        System.out.println("Execution done");
    }
}

When you run this program, it will output:

finally block is always executed

Exception in thread “main” java.lang.ArithmeticException: / by zero

 

 

 

 

 

 

 

 

 

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close