Can statements in the finally block go unexecuted

The finally block can go unexecuted if we call System.exit in the try block:

public class Finally {
     public static void main(String[] args) {
         try {
             System.out.println("Start");
             System.exit(0); // same as using Runtime.getRuntime().exit(0);
         }
         finally {
             System.out.println("Hello");
         }
    }
}

Hence, be careful to clear up resources before calling System.exit or Runtime.getRuntime().exit. The best practise would be to avoid the use of these functions. Rather, use RuntimeException s, in case you want exit when an exceptional condition occurs.

Comments