import java.io.*;public class ShutdownDemo { private FileWriter fw_log; private BufferedWriter bw_log; // constructor that opens the log file public ShutdownDemo() throws IOException { fw_log = new FileWriter("log.txt"); bw_log = new BufferedWriter(fw_log); // register the shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { endApp(); } });; } // do some application processing and write to the log file public void processApp1() throws IOException { bw_log.write("testing"); bw_log.newLine(); } // do some application processing resulting in an exception public void processApp2() { throw new RuntimeException(); } // close the log file public void endApp() { try { bw_log.close(); } catch (IOException e) { System.err.println(e); } } public static void main(String args[]) throws IOException { // create an application object ShutdownDemo demo = new ShutdownDemo(); // do some processing demo.processApp1(); // do some more processing that results in an exception demo.processApp2(); }}