I have some code which creates a JarFile and a URLClassLoader, both of which I want to close at the end. Naturally, I decided to use the finally block to deal with the cleanup:
JarFile jar = ...;
URLClassLoader loader = ...;
try {
// work ...
} finally {
jar.close();
loader.close();
}
However, both close() invocations can throw an exception, so if jar.close() would throw an exception, then loader.close() would not be reached. One way I thought about working around this is by surrounding jar.close() with a try-catch block:
JarFile jar = ...;
URLClassLoader loader = ...;
try {
// work ...
} finally {
try {
jar.close();
} catch(IOException e) {
}
loader.close();
}
But this seems ugly and excessive. Is there an elegant way of dealing with cleanup-related exceptions in finally blocks?