Listing 5: File Manage.java — Illustrates closing a resource while letting an exception pass up the call stack

import java.io.*;
class Manage
{
    public static void f(String fname)
        throws IOException
    {
        FileReader f = null;
        try
        {
            f = new FileReader(fname);
            System.out.println("File opened");
            int c = f.read();   // read a byte
            // ...
        }
        finally
        {
            if (f != null)
            {
                System.out.println("File closed");
                f.close(); // beware lost exception!!!
            }
        }
    }
       
public static void main(String[] args)
    {
        try
        {
            f(args[0]);
        }
        catch (Exception x)
        {
            System.out.println(x);
        }
    }
}
— End of LIsting —