Timo said:
try
{
Blah blah = new Blah();
blah.work(); // throws exception
Blah2 blah2= new Blah2();
...
}
catch..
finally
{
if(blah!=null)blah.cleanup();
if(blah2...
}
Timo,
I think you're missing a distinction. Local variables that are declared
and not initialized are *not* given an initial value of null. They are
considered no definitely assigned, and it is a compile-time error to
access them before assigning a value.
I appreciate that you may be suggesting a change to the language to work
around this, but you haven't been clear on what that is. Do you want to
give all local reference variables an initial value of null? Do you
just want to do that for variables declared in try blocks? Or do you
wish to specify that the compiler has to differentiate based on the
location where the exception is thrown, so that all variables that
haven't been definitely assigned at that point are set to null at the
beginning of the try block? Is it only reference variables local to the
block that should be made available in the finally block, or primitives
as well; and if the latter, are they also to be artificially definitely
assigned, and to what values?
All of those options seem to me to have substantial disadvantages, but
it's hard to articulate them when you haven't defined what you want.
All of this could be easily avoided if you would simply not try to
combine try/catch and try/finally in the same construct. Doing so leads
to a large number of awkward problems... mostly because you want
try/catch to surround all the code that could throw an exception, but
try/finally to surround just that code where cleanup is necessary.
Because of this, I find it better to wrote:
try
{
final PreparedStatement stmt = con.prepareStatement(...);
try
{
...
}
finally
{
con.close();
}
}
catch (SQLException e)
{
...
}
Typically, though, I tend to factor code at a smaller granularity than
that, so the try/catch block would be in one method, and the try/finally
in a separate method. It seems that dealing with an SQLException and
running a query (including closing the connection, of course) are
separate enough that they don't need to belong in the same method.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation