Why do I get IO resource opened but not safely closed
Hi All,
Why do I get this warning with the following code?
Properties props = new Properties();
Reader reader = null;
try {
reader = new FileReader(configFile);
props.load(reader);
reader.close();
} finally {
if (reader != null) {
reader.close();
}
}
This is with IDEA 10.5 thanks
请先登录再写评论。
Hi Dan,
Why do you call 'close()' twice?
Regards, Denis
Well it happens with or without that second close call. The method itself thows IOException. In other words I want to thow an exception if we can't read the file but ensure that the Reader is closed.
Enable the "Allow resource to be opened inside a 'try' block" checkbox in the inspections settings and the inspection will not warn on your code. You may have to resize the settings screen to see the checkbox.
By default the inspection expects the code to look like this, which is the recommended way:
Bas
Ahh. OK thanks! :)
One badly reported warning is:
This is filly legal code and in reality in the most cases will be used some utility method instead of plain close. It will be good to provide and option to define "allowed method" to close resource, it will be very useful. It will force people to reuse existing utility classes.
regards, Alex
The inspection should already recognize utility methods to close streams quietly. Code it like this to prevent the warning, or use the "Allow resource to be opened inside a 'try' block" checkbox:
Bas
I use the latest 10.5.1 idea, but there is no support for utility classes
didn't realize how
it's not an option for me because i started inspections over existing codebase and i can't change code for such reason.
the only appropriate solution for me, is to provide a list of allowed methods/patterns to count resource as safely released, becuase we have a very sofisticated resource management. The same true for jdbc resources and sockets. Also, this will help to maintain code style and reuse code.
Best regards, Alex.
Message was edited by: Alexander Ashitkin
IOUtils.closeQuietly() or any other close method should automagically be detected as closing a stream. If it doesn't that's a bug, please submit it to YouTrack with sample code.
Bas
You do not have to change code if you enable the checkbox in the inspection settings.
Bas
Hi, Lars.
I reported IDEA-72042 because i can't make it work. Hope will be implemented sometime.
thanks inadvance, Alex