Mar 22, 2018

The finally block is a key tool for preventing resource leaks.

When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

finally {
    if (printWriter != null) { 
        System.out.println("Closing PrintWriter");
        out.close(); 
    } else { 
        System.out.println("PrintWriter not open");
    }