Re: different try-finally approach
Tom Anderson wrote:
On Mon, 3 Aug 2009, Pitch wrote:
In java it is common to check if the resource is null in finally
statement, before closing it:
public void doSomething() throws MyResourceException
{
MyResource res = null;
try
{
res = new MyResource();
// do something
}
finally
{
if (res != null) res.close()
}
}
But in some other languages this is the preferred way:
public void doSomething() throws MyResourceException
{
MyResource res = new MyResource();
try
{
// do something
}
finally
{
res.close()
}
}
The first example ensures nothing more than the second one, right? If
the constructor throws an exception the "res" is null, so it can't be
closed anyways.
So, my question is - why the extra coding in java? Am I missing
something?
I'm not aware that the former is 'preferred' in java. I certainly
strongly prefer the latter. Indeed, i consider the former an error, and
i'll fix it when i see it in code.
tom
It's possible that a code snippet here or there gave the OP a mistaken
impression. For example, the exception handling discussion in the Java
tutorial does have something like
finally {
if (out != null) {
out.close();
} else {
...
}
}
although there are catch blocks (the example method is handling all
exceptions, not rethrowing any), and "out" is a PrintWriter that could
in fact be null in the finally block (the PrintWriter ctor, IOW, is
wrapping a FileWriter ctor which is what could throw an exception).
However, the discussion is split out among a number of pages and hasty
scanning of the material might lead to a wrong conclusion.
Although if you're Googling then the very first link you run across
using the keywords "Java finally" is
http://www.javapractices.com/topic/TopicAction.do?Id=25, where Style 1
has it that if you're rethrowing the exception, that you follow the
style of the second example given by the OP.
In a nutshell it's not clear to me why the OP thought that example 1 was
the "common" or "preferred" way, unless it was careless reading.
Understanding what can throw exceptions, where you wish to handle
exceptions, and what resources need to be disposed of, always leads you
to a simple and correct way of writing your exception handling code,
IMHO. I have no idea why it's such a mysterious topic.
AHS