Why does this code generate a “Potential resource leak” warning?

南楼画角 提交于 2020-01-01 09:34:28

问题


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.


回答1:


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);
    }
}



回答2:


What if you move both open and close to first try clause? They throw the same type of exception. And remove the if os != null.




回答3:


My guess is it's because you have if (os != null) before closing. Since it's conditional it's possible that the OutputStream is not closed.

What happens if you try:

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 {
        try {
            os.close();
        } catch (IOException ignored) {
        }
    }
}


来源:https://stackoverflow.com/questions/11786637/why-does-this-code-generate-a-potential-resource-leak-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!