I have a Closeable
that needs to clean up multiple resources in the close()
method. Each resource is a final
class
that I cannot modify. None of the included resources are Closeable
or AutoCloseable
. I also need to call super.close()
. So it appears that I cannot handle any of the resources* using try-with-resources
. My current implementation looks something like this:
public void close() throws IOException {
try {
super.close();
} finally {
try {
container.shutdown();
} catch (final ShutdownException e) {
throw new IOException("Handling ShutdownException: ", e);
} finally {
try {
client.closeConnection();
} catch (final ConnectionException e) {
throw new IOException("Handling ConnectionException: ", e);
}
}
}
}
I'd prefer a solution with less crazy nesting but I can't figure out how to take advantage of try-with-resources
or any other features to do that. Code sandwiches don't seem to help here since I'm not using the resources at all, just cleaning them up. Since the resources aren't Closeable
, it's unclear how I could use the recommended solutions in Java io ugly try-finally block.
* Even though the super
class is Closeable
, I cannot use super
in a try-with-resources
because super
is just syntactic sugar and not a real Java Object
.
Aucun commentaire:
Enregistrer un commentaire