The finally Block
Since the finally block executes regardless of an exception in the try block, it is helpful in more ways than one. The finally block can be used as a tool to prevent resource leaks. The code to close a file or any resources can be placed in a finally block to ensure that the job is done. It also prevents the cleanup code from bypassing the return, break or continue statements. It’s a good practice to implement the finally block, even when no exceptions are anticipated.
When used in different cases, the finally block results in different outputs. Let us discuss them in brief and understand their use.
Case 1: There is no exception in the code
When the try block encounters no exception in its code, the try block is executed and then the finally block. The catch block, if it exists, is ignored.
try
{
int a = 10, b = 5;
int Result = a/b;
System.out.println("Result = " + Result);
}
catch
{
System.out.println("The operation is not possible with b = 0");
}
finally
{
System.out.println("END");
}
You can also try this code with Online Java Compiler
Run Code
Output:
Result = 2
END
A return statement in the try block
A subroutine uses a return statement to return to the method that called it. If the try block contains a return statement and has a finally block following it, the finally block is first executed, and then the control returns to the calling method.
public static void main(String[] args) {
division();
System.out.println("-----------------");
}
public static void division() {
try
{
int a = 10, b = 5;
int Result = a/b;
System.out.println("Result = " + Result);
return;
}
finally
{
System.out.println("END");
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
Result = 2
END
----------------
A System.exit(0) statement in the try block
The System.exit(0) statement, unlike the return statement, completely exits the program. It means that the finally block will not be executed as well. However, if an exception occurs in the System.exit(0) method, then the finally block gets executed.
try
{
int a = 10, b = 5;
int Result = a/b;
System.out.println("Result = " + Result);
System.exit(0);
}
finally
{
System.out.println("END");
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
Result = 5
Case 2: Exception is handled by the catch block
Now, let us assume that the try block finds an exception in its code. The catch block that contains the code to be executed on encountering an exception is chosen. If a finally block exists after the catch block, it is executed.
try
{
int a = 10, b = 0;
int Result = a/b;
System.out.println("Result = " + Result);
}
catch
{
System.out.println("The operation is not possible with b= 0");
}
finally
{
System.out.println("END");
}
You can also try this code with Online Java Compiler
Run Code
Output:
The operation is not possible with b = 0
END
Case 3: Exception in finally block
The finally block does not execute when there is an exception within the block itself. The exception encountered can be handled using another try-catch block within the finally block.
int a = 10, b = 5;
try
{
int Result = a*b;
System.out.println("Product = " + Result);
}
finally
{
System.out.println("Quotient = " + (a/b));
}
}
You can also try this code with Online Java Compiler
Run Code
Output:
Product = 50
Exception in thread "main" java.lang.ArithmeticException: / by zero
Practice by yourself on java online compiler.
In conclusion, the finally block is not executed in the following cases:
-
Due to the death of a thread.
-
Due to the System.exit(0) statement in the try block.
- The presence of an exception in the finally block.
Must Read Conditional Statements in Java and Hashcode Method in Java
FAQs
Q: What is the difference between an error and an exception?
-
Errors occur at runtime, while exceptions may occur at runtime or compile time.
-
Errors are not recoverable, whereas exceptions can be recovered and handled by try-catch blocks.
-
Errors belong to the java.lang.Error package and exceptions belong to the java.lang.Exception package.
Q: What are the types of exceptions in Java?
-
Checked exceptions are compile-time exceptions that are checked by the compiler. If not handled, we get a compile error. A few examples of checked exceptions are IOException, ClassNotFoundException, InterruptionException, etc.
- Unchecked Exceptions are not checked by the compiler, and do not throw a compile error on ignoring it. Examples of unchecked exceptions are NullPointer Exception, Arithmetic Exception, etc.
Key Takeaways
We all have encountered exceptions in the past or will face them in the future. Handling exceptions with finally is known to be more efficient and preferred, and hence, knowledge about it is essential. This blog covers the basics of exception handling and gives a detailed explanation of the finally block. We have also discussed the use of finally in different cases with examples.
Related Links:
Exceptions in Java- Hierarchy, types and Errors.
Checked and Unchecked Exceptions in Java
Exception handling with try-catch and finally
Introduction to Java
Check out the official Coding Ninjas Blog site and visit our Library for more.