We have a class we've written which opens up a connection to a server. When you're done with it, you need to either tell it to commit
if everything was successful, or tell it to rollback
if something went wrong. So right now we have a lot of spots in our code that look like this:
OurConnectionClass conn = null;
try {
conn = OurConnectionClass(parameters);
// Do some stuff here...
conn.commit();
} catch (Throwable t) {
if (conn != null) {
conn.rollback();
}
throw t;
}
If you forget to commit or rollback, there's no immediate issues, but eventually you exhaust a connection pool and then have to figure out where you made a mistake.
I'd like to find a way so OurConnectionClass
implements AutoClosable
, so I could do somsething like this instead:
try (OurConnectionClass conn = new OurConnectionClass(parameters)) {
// Do some stuff here...
}
I feel like there has to be a way to do this, but I'm not seeing it. AutoCloseable
only calls a close
method, with no arguments passed to it. As far as I can see, there's no way to know whether close is being called because the end of the try block was successfully reached or because an exception was thrown.