Tuesday 31 March 2009

Simple Resource Handling in Java

Now we've seen how not to do it, let's see the simple solution and its obvious pitfalls.

void foo() throws IOException {
SomeResource r = new SomeResource();
try {
//do some stuff with r
}
finally {
r.close();
}

This is a trivial solution, in all likelihood good enough, but it has an obvious flaw: if close() throws an exception, then this masks any exception that occured in the try block. This is not a major flaw, since the code still throws an IOException from the correct function, but it may hinder any code handling the error, or give misleading error messages or diagnostics.

For multiple resources we need nested try blocks:

void foo() throws IOException {
SomeResource r1;
try {
//open r1 etc.
AnotherResource r2;
try {
//open r2
}
finally {
r2.close();
}
finally {
r1.close();
}
}

This has the additional problem that the code is looking rather convoluted.

No comments:

Post a Comment