Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code generate a "Potential resource leak" warning?

Eclipse (Juno) gives the following warning:

Potential resource leak: 'os' may not be closed

at the first line of the try body in this code:

static void saveDetails(byte[] detailsData) {
    OutputStream os = null;
    try {
        os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);
        os.write(detailsData);
    } catch (IOException e) {
        Log.w(LOG_TAG, "Unable to save details", e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException ignored) {
            }
        }
    }
}

The method openFileOutput is declared to throw a FileNotFoundException.

Is this a false positive? It seems like a fairly vanilla execution path analysis.

like image 952
Ted Hopp Avatar asked Aug 02 '12 22:08

Ted Hopp


1 Answers

In my opinion, this is a false positive. Your resource is closed in a "finally" block, so I cannot see what could go wrong here.

As a sidenote, if you are using Java 7, I'd recommend using the "try-with-resources" idiom.

static void saveDetails(byte[] detailsData) {    
    try (OutputStream os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);) {
        os = sContext.openFileOutput(DETAILS_FILE_NAME, Context.MODE_PRIVATE);
        os.write(detailsData);
    } catch (IOException e) {
        Log.w(LOG_TAG, "Unable to save details", e);
    }
}
like image 77
Olivier Croisier Avatar answered Sep 28 '22 09:09

Olivier Croisier