• The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
  • Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
  • That means finally is a block always associated with try catch to maintain cleanup code. The general form is :

Syntax

try
{
    //risky code
}
catch(Exception e)
{
    //handling code
}
finally
{
    //cleanup code
}

Example:

class FinallyDemo
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
finally
{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}

Output

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed

Note

  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • For each try block, there can be zero or more catch blocks, but only one finally block.
  • The finally block will not be executed if program exits due to any reason, such as calling System.exit() or by causing a fatal error that causes the process to abort.
Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment