Frage

I need to read a properties file. I am using BufferedReader and FileReader for this purpose. I am initializing BufferedReader to null before the try section and initializing in the try section. In finally, I am closing the reader. At this point, I am getting the error mentioned in the title.

The complete code is below

public void getPageTitleProperties() throws IOException
    {

        BufferedReader br = null;
        String lhs, rhs;
        try 
        {
            br = new BufferedReader(new FileReader("res" + File.separator + "pagetitle.properties"));
            String line;
            while ((line = br.readLine()) != null) 
            {
                String [] keyvalue = line.split("=");
                lhs = keyvalue[0];
                rhs = keyvalue[1];
                expectedTitles.put(lhs, rhs);
            }
        }
        catch (RuntimeException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            br.close();
        }

        System.out.println("Expected URLs and Titles");
        for (String url : expectedTitles.keySet())
        {
            System.out.println(url + ":" + expectedTitles.get(url));
        }

    }

The bug details are -

How can I get rid of this error? I have tried initializing BR to non-null, initializing it in the try block (which does not work as the variable cannot be resolved in the finally block :)). In some similar posts, folks have mentioned this as possible false negative. I have also referenced to - http://findbugs.sourceforge.net/bugDescriptions.html#NP_GUARANTEED_DEREF, but could not figure how to get rid of the bug.

War es hilfreich?

Lösung

How can I get rid of this error?

The problem is that if the BufferedReader or FileReader constructor throws an exception, br will be null but you're still unconditionally calling br.close(). Check whether br is null before you close it in the finally block:

finally {
    if (br != null) {
        br.close();
    }
}

Alternatively, assign it before the try block:

BufferedReader br = new BufferedReader(...);
try {
    ...
} catch (...) {
    ...
} finally {
    br.close(); // br will definitely not be null
}

Or even better in Java 7, use a try-with-resources statement:

try (BufferedReader br = new BufferedReader(...)) {
    ...
} catch (...) {
    ...
}

Note that currently your catch blocks are dumping the error but then continuing as if nothing's happened - whereas I'd expect the exception to be propagated to the caller. What do you want to happen if the file can't be read? (With the second and third changes I've suggested, you'd still be swallowing exceptions for actual reading, but not on opening the file.)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top