finally block

For Java 11 Certification Exam Practice Questions, refer

In this article, let us discuss the finally block in Java, from the Java 11 certification perspective.

What is significance of the finally block?

The finally block executes when the try block exits, successfully or with an exception. So this block usually contains the clean up code. Performing clean up in every case ensures that there are no resource leaks.

In the below example, the scanner is closed in the finally block.

Scanner scanner = null;
try {
        scanner = new Scanner(new File("a.txt"));
        return scanner.nextLine();
} finally {
       if (scanner != null) {

Will the finally block be executed always?

The finally block may not execute if the JVM exits while the try or catch code is being executed. The finally block does not execute in the below code, as the System.exit() is called as it terminates the JVM.



For more information on this topic, you can refer

Leave a Reply

Your email address will not be published. Required fields are marked *