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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package com.turreta.exception; public class SkipFinalllyExample { public static void main(String[] args) { try { throwExceptionNow(); } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("Finally!"); } } private static void throwExceptionNow() throws Exception { throw new Exception("Test exception"); } } |
The statement at line 11 will consistently execute whether or not an exception occurs. When we run the codes, we get the following result.
1 2 3 4 | Finally! java.lang.Exception: Test exception at com.turreta.exception.SkipFinalllyExample.throwExceptionNow(SkipFinalllyExample.java:17) at com.turreta.exception.SkipFinalllyExample.main(SkipFinalllyExample.java:7) |
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.
1 | System.exit(0); |
If we put this statement in the catch clause just before the e.printStackTrace(), the codes will never display the word “Finally!”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.turreta.exception; public class SkipFinalllyExample { public static void main(String[] args) { try { throwExceptionNow(); } catch (Exception e) { e.printStackTrace(); /* * This shutdowns the whole JVM and effectively skipping the finally clause */ System.exit(0); } finally { System.out.println("Finally!"); } } private static void throwExceptionNow() throws Exception { throw new Exception("Test exception"); } } |
When we run these Java codes, they will skip and not execute the finally clause and print out the following result.
1 2 3 | java.lang.Exception: Test exception at com.turreta.exception.SkipFinalllyExample.throwExceptionNow(SkipFinalllyExample.java:18) at com.turreta.exception.SkipFinalllyExample.main(SkipFinalllyExample.java:7) |
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.