Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java finally Keyword

  • • 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:
cclass 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.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext