Understanding the Finally Block in Java: Ensuring Code Execution
Discover the role of the finally
block in Java exception handling. This essential component always executes after a try
or catch
block, ensuring that critical cleanup code runs regardless of whether an exception was thrown. Learn how to effectively implement the finally
block in your Java applications.
The Finally Block in Java
The finally block follows a try block or a catch block. A finally block of code always executes, regardless of whether an exception occurs.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
Syntax: Finally Block
A finally block appears at the end of the catch blocks and has the following syntax:
Code Snippet
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
} finally {
// The finally block always executes.
}
Points To Remember While Using Finally Block
- A catch clause cannot exist without a try statement.
- It is not compulsory to have finally clauses whenever a try/catch block is present.
- The try block cannot be present without either a catch clause or a finally clause.
- No code can be present between the try, catch, and finally blocks.
- The finally block is not executed if the exit() method is called before the finally block, or if a fatal error occurs during program execution.
- The finally block is executed even if the method returns a value before the finally block.
Why Java Finally Block Is Used?
The Java finally block can be used for cleanup (closing) connections, files opened, streams, etc., that must be closed before exiting the program. It can also be used to print some final information.
Java Finally Block Example
Here is a code segment showing how to use finally after try/catch statements after handling an exception. In this example, we're creating an error by accessing an element of an array using an invalid index. The catch block handles the exception and prints the message. Now, in the finally block, we're printing a statement signifying that the finally block is getting executed.
Code Snippet
package com.tutorialsarena;
public class ExcepTest {
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: Index 3 out of bounds for length 2
First element value: 6
The finally statement is executed
More Examples
Example 1
Here is a code segment showing how to use finally after try/catch statements even when the exception is not handled. In this example, we're creating an error by accessing an element of an array using an invalid index. As the catch block is not handling the exception, we can check the output to see that the finally block is still executed.
Code Snippet
package com.tutorialsarena;
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three: " + a[3]);
} catch (ArithmeticException 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
First element value: 6
The finally statement is executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 2
at com.tutorialsarena.ExcepTest.main(ExcepTest.java:8)
Example 2
Here is a code segment showing how to use the finally block where a method can return a value within the try block. In this example, we're returning a value within the try block. We can check the output that the finally block is executed even after the method has returned a value to the caller function.
Code Snippet
package com.tutorialsarena;
public class ExcepTest {
public static void main(String args[]) {
System.out.println(testFinallyBlock());
}
private static int testFinallyBlock() {
int a[] = new int[2];
try {
return 1;
} 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");
}
return 0;
}
}
Output
First element value: 6
The finally statement is executed
1