finally block

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

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) {
            scanner.close();
        }
}

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.

try{
    System.exit(0);
}
finally{
    System.out.println("finally");
 }

References

For more information on this topic, you can refer https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

Leave a Reply

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