How to Skip A Finally Statement in Java
A common interview question for Java developers is to write some code inside a try / catch / finally
statement so that the finally statement is not reached. At first glance, this is not possible.
A finally
statement in Java is used in conjunction with a try
/catch
statement. The finally
statement contains a block of code that is guaranteed to be executed, regardless of whether an exception is thrown or caught in the try
block.
The finally
statement is typically used to perform clean-up operations, such as releasing resources that were acquired in the try
block, or logging any relevant information about the state of the program when an exception occurs.
Here is a simple example of a try
/catch
/finally
statement in Java:
try {
// code that may throw an exception
} catch (Exception e) {
// code to handle the exception
} finally {
// code that will always be executed, regardless of whether an exception is thrown
}
In this example, the code in the try
block may throw an exception. If an exception is thrown, it will be caught by the catch
block and handled appropriately. Regardless of whether an exception is thrown or caught, the code in the finally
block will always be executed.
It's important to note that if the finally
block itself throws an exception, this exception will overwrite the exception that was thrown in the try
block, making it more difficult to determine the root cause of the problem.
However, here is one way to avoid going through the finally statement:
try {
System.exit(1);
} catch (Exception e) {
System.out.println("Nothing is caught here.");
} finally {
System.out.println("Finally block is never executed.");
}
This code creates a simple Java program that demonstrates how a finally
block is not executed if the program exits using System.exit(1)
before the finally
block is reached.
Here's what happens when the code is executed:
- The
main
method is called, starting the program. - The
try
block contains a single line of code,System.exit(1)
, which immediately terminates the Java Virtual Machine (JVM) and the program. - Since the
System.exit(1)
call causes the JVM to exit, the rest of thetry
/catch
/finally
block is not executed, including thefinally
block. - As a result, the output of the program is nothing, as the message "Finally block is never executed." is never printed.
It's worth noting that when System.exit(1)
is called, it terminates the entire JVM, including all threads and all other non-daemon threads. This means that no other code can be executed after System.exit(1)
, including any code in a finally
block.