Java, Software Development

Java – How to skip and not execute the finally clause

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

They say that when an exception occurs, the finally clause, if available, will consistently execute no matter what except. That statement is not always accurate in real life.  This post shows how our Java codes can skip and not complete the finally clause.

Sample Java Codes Always Run the Finally clause

Consider the following Java codes that have the main method and another static method. Moreover, the Java program has try-catch-finally clauses for us to play around with. To simulate an actual exceptional event, we explicitly throw an Exception object from one method. Then, we handle the exceptional event in the main method.

The statement at line 11 will consistently execute whether or not an exception occurs. When we run the codes, we get the following result.

Make Codes Skip The Finally clause

If the finally clause always executes, how can we skip it in our Java codes. Consider the following sample codes. First, we could use this command to terminate the whole JVM because the codes run the finally clause. Therefore, it can skip the finally clauses.

If we put this statement in the catch clause just before the e.printStackTrace(), the codes will never display the word “Finally!”

When we run these Java codes, they will skip and not execute the finally clause and print out the following result.

Suppose we used the return keyword instead of the System.exit(0) command. Would the codes still skip and not run the finally clause?

This post is part of a reboot Java tutorial.

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like