Re: different try-finally approach
Pitch wrote:
So, my question is - why the extra coding in java? Am I missing
something?
Daniel Pitts wrote:
MyResource res1 = new MyResource("a");
MyResource res2 = new MyResource("b"); // throws exception
oops, res2 is null, but res1 is not.
This is why I miss RAII from C++.
Yeah, there's a fair amount of boilerplate in opening multiple interdependent
resources that you have to grind out yourself in Java.
You can get pretty close to RAII in Java, though you might need to very
gingerly spike a finalizer into the mix. You just have to plod through the
source lines that entails.
IDEs today sport macro facilities that let you insert such boilerplate into
your source with a few keystrokes. E.g.,
{
final Resource r1;
final Resource r2;
try
{
r1 = Resource.getInstance();
r1.open();
}
catch ( ResourceException re )
{
logger.error( "Unable to open r1", re );
return;
}
try
{
r2 = Resource.getInstance();
r2.open();
}
catch ( ResourceException re )
{
logger.error( "Unable to open r2", re );
close( r1 );
return;
}
assert r1 != null && r2 != null;
assert r1.isOpen() && r2.isOpen();
try
{
// TODO:
}
finally
{
close( r1 );
close( r2 );
}
}
--
Lew