Finally block in Java

Java Finally block – Exception handling

The finally block in Java is where crucial code is executed, such shutting a connection, among other things.The finally block in Java is always executed, regardless of whether an exception is handled. As a result, it includes all the required statements that must be printed whether or not an exception occurs.The try-catch block is followed by the finally 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