Java - When finally code block is executed

By xngo on June 19, 2019

The code block inside finally statement is called after exception is thrown or after a return statement. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.

Here are some examples.

public class FinallyBlock {
 
    public static void main(String[] args) {
 
        finallyRanAfterException();
        finallyRanAfterReturn();
 
    }
 
    public static void finallyRanAfterException() {
        try {
            // Simulate exception is thrown.
            throw new RuntimeException("Throw an exception");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
 
        finally {
            System.out.println("Finally code block will run after an exception is thrown.");
        }
    }
 
    public static int finallyRanAfterReturn() {
        try {
            return 42;
        }
 
        finally {
            System.out.println("Finally code block will run after the 'return' statement.");
        }
    }
 
}

Output

java.lang.RuntimeException: Throw an exception
    at net.xngo.tutorial.java.lang.FinallyBlock.finallyRanAfterException(FinallyBlock.java:17)
    at net.xngo.tutorial.java.lang.FinallyBlock.main(FinallyBlock.java:8)
Finally code block will run after an exception is thrown.
Finally code block will run after the 'return' statement.

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/lang/FinallyBlock.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.