Finally Block in Java

Introduction

It is a special block in Java. It is a block in a program that always executes. If we want to perform an important task and want it to execute always in any condition then we use a finally block in Java.

Finally Block in Java

The following describes the finally block in Java:

  • In Java, finally is a special keyword.
     
  • It always executes independent of any condition.
     
  • It is optional in Java.
     
  • It should be after the try-catch block in Java.
     
  • For a single try block, there can be a maximum of one finally block in Java.
     
  • Generally we use a finally for closing the connections or closing the file and so on.



    finally always executes



Examples of Finally in Java

No Exception Condition

package demo;

public class Demo

    public static void main(String args[])

    {

        try

        { 

            int fig=36/6; 

            System.out.println(fig); 

        } 

        catch(NullPointerException e)

        {

            System.out.println(e);

        } 

        finally

        {

            System.out.println("ALWAYS EXECUTE");

        } 

        System.out.println("#**.......**#"); 

    } 

}

 

Output

when no exception


Exception Condition

 

package test;

public class Test

{

    public static void main(String args[])

    {

        try

        {

            int fig=36/0; 

            System.out.println(fig); 

        } 

        catch(NullPointerException e)

        {

            System.out.println(e);

        }

        finally

        {

            System.out.println("ALWAYS EXECUTE");

        } 

        System.out.println("#**.......**#"); 

    } 

}

 

Output

when exception


Exception Condition, But Handled

 

package trial;

public class Trial

    public static void main(String args[])

    { 

        try

        { 

            int fig=36/0; 

            System.out.println(fig); 

        } 

        catch(ArithmeticException e)

        {

            System.out.println(e);

        } 

        finally

        {

            System.out.println("ALWAYS EXECUTE");

        } 

        System.out.println("#**.......**#"); 

    } 

}

 

Output

exception but handled


Summary

 

This article has explained the finally block in Java.

Up Next
    Ebook Download
    View all
    Learn
    View all