Java, Software Development

Java – How to skip and not execute the finally clause

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.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like