Question

I'm a beginner still, and currently learning about handling exceptions. The exercise in my book I'm trying to figure out tells me to add a Finally block to close out the file I opened, and I don't understand what I'm doing wrong. Keep in mind the file name and path are fake but here is what I have:

public static String readLineWithFinally()
{
    System.out.println("Starting readLineWithFinally method.");
    RandomAccessFile in = new RandomAccessFile("products.ran", "r");
    try
    {                     
        String s = in.readLine();
        return s;
    } 
    catch (IOException e)
    {
        System.out.println(e.toString());
        return null;
    }
    finally
    {
        try
        {
                in.close();
        }
        catch (Exception e)
        {
            System.out.println("Generic Error Message");
        }
    }
}    
Was it helpful?

Solution 2

The code that you posted shouldn't compile, as RandomFile(String, String) can possibly throw FileNotFoundException. As such, we must include it in the try block.

System.out.println("Starting readLineWithFinally method.");
RandomAccessFile in = null;
try {
    in = new RandomAccessFile("products.ran", "r");
    String s = in.readLine();
    return s;
} catch (IOException e) {
    System.out.println(e.toString());
    return null;
} finally {
    try {
        if(in != null) {
            in.close();
        }
    } catch (Exception e) {
        System.out.println("Generic Error Message");
    }
}

OTHER TIPS

To add on to Taylor Hx's answer, you can take advantage of Java 7's try-with-resources construct to avoid having to use finally altogether in your case.

public static String readLineWithFinally() {
    System.out.println("Starting readLineWithFinally method.");
    try (RandomAccessFile in = new RandomAccessFile("products.ran", "r")) {
        return in.readLine();
    } catch (IOException e) {
        System.out.println(e.toString());
        return null;
    }
}

You'll also want to be certain that your usage is consistent with what the API mandates for RandomAccessFile.

Keep in mind the file name and path are fake but here is what I have:

That is why you will have a FileNotFoundException while creating RandomAccessFile("products.ran", "r") with read access mode "r".

From the documentation: RandomAccessFile(String name, String mode)

This constructor throws a FileNotFoundException if the mode is "r" but the given string does not denote an existing regular file, or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top