Overview
In this article, we explore the finally keyword in Java. We will see how it is used within the try/catch block during exception handling. We will discuss how it is used, where it is used, and why it is used. We will also discuss where it is not applicable in exception handling.
So, what is this finally keyword?
finally is used to define a block of code that always executes whether the exception is caught or not. It executes when the try block exits.
A Common Example
public class FinallyClass{
public static void finallyMethod() {
int num1 = 1;
int num2 = 0;
try {
int result = num1/num2;
}
catch(ArithmeticException e)
{
e.printStackTrace();
System.out.println("In catch block");
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result of the above execution is:
java.lang.ArithmeticException: / by zero
at Tests.A.finallyMethod(A.java:9)
at Tests.A.main(A.java:21)
In catch block
In finally block
In the above example, dividing a number by zero results to an ArithemticException as shown. However, it is evident that the finally block executes.
Let’s see another example where the try executes successfully:
public class FinallyClass{
public static void finallyMethod() {
int num1 = 1;
int num2 = 2;
try {
int result = num1/num2;
System.out.println("Result is: "+result);
}
catch(ArithmeticException e)
{
e.printStackTrace();
System.out.println("In catch block");
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result is:
Result is: 0
In finally block
Also, we can use the finally block with the try block only, that is, without the catch block. Let’s see an example:
public class FinallyClass{
public static void finallyMethod() {
int num1 = 1;
int num2 = 2;
try {
int result = num1/num2;
System.out.println("Result is: "+result);
}
//only finally block
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result is:
Result is: 0
In finally block
and when an exception exists:
public class FinallyClass{
public static void finallyMethod() {
int num1 = 1;
int num2 = 0;
try {
int result = num1/num2;//Will result to ArithmeticException
System.out.println("Result is: "+result);
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
and the result is:
In finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Tests.A.finallyMethod(A.java:9)
at Tests.A.main(A.java:18)
Therefore, we have seen that the finally block will execute whether an exception exists or not or regardless of what happens with the try block.
So, Why is the finally keyword/block useful?
finally block is used in executing clean up code. For example, freeing threads, closing files, and closing connections because it executes regardless of the existence of an exception.
Note: You should use try-with-resources instead of finally to close files or resource recovery.
So, when is the finally block not executed?
There are a few instances when the finally block is not executed. Let us look at some of them:
When we invoke System.exit
public class A {
public static void finallyMethod() {
int num1 = 1;
int num2 = 2;
try {
int result = num1/num2;
System.out.println("Result is: "+result);
System.exit(1); //using System.exit
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result is:
Result is: 0
Another case is when the JVM reaches an infinite loop. For example:
public class A {
public static void finallyMethod() {
int num1 = 1;
int num2 = 2;
try {
int result = num1/num2;
System.out.println("Result is: "+result);
while(true) { //infinite while loop
}
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result is:
Result is: 0
Another instance is when we invoke halt. For example:
public class A {
public static void finallyMethod() {
int num1 = 1;
int num2 = 2;
try {
int result = num1/num2;
System.out.println("Result is: "+result);
Runtime.getRuntime().halt(1);//invoking halt
}
finally {
System.out.println("In finally block");
}
}
public static void main(String[]args) {
finallyMethod();
}
}
The result is:
Result is: 0
Therefore, there exists areas in which the finally block is not always executed.
Mind teaser Question
Given the code below, what will be the result of compiling and executing the LearningException class?
public class LearningException {
public static void main(String[] args) {
try { //outer
try { //inner
System.out.println(1/0);
} catch(ArithmeticException e) {
System.out.println("INNER");
} finally {
System.out.println("FINALLY 1");
}
} catch(ArithmeticException e) {
System.out.println("OUTER");
} finally {
System.out.println("FINALLY 2");
}
}
}
Ans: INNER, FINNALLY 1, FINALLY 2
Reason: System.out.println(1/0);′ throws ArithmeticException, handler is available in inner catch-block, it executes and prints “INNER“ to the console. Once an exception is handled, no other catch block will get executed unless the exception is re-thrown. Inner finally-block gets executed and prints “FINALLY 1“ to the console. Rule is finally-block always gets executed, so outer finally-block gets executed and prints “FINALLY 2“ to the console.
Conclusion
In this article, we set out to learn about the finally block, where it is used, and where it is not applicable. We will look into advanced cases in future articles.
Nice coding.