Background: I use the Java class InitialDirContext
to access LDAP directories. Unfortunately, it does not implement interface AutoCloseable
, so it cannot be used in try-with-resources blocks.
Here is the original code I wrote: (inspired by this answer)
final Properties props = new Properties();
// Populate 'props' here.
final InitialDirContext context = new InitialDirContext(props);
Exception e0 = null;
try {
// use 'context' here
}
catch (Exception e) {
// Only save a reference to the exception.
e0 = e;
// Why re-throw?
// If finally block does not throw, this exception must be thrown.
throw e;
}
finally {
try {
context.close();
}
catch (Exception e2) {
if (null != e0) {
e0.addSuppressed(e2);
// No need to re-throw 'e0' here. It was (re-)thrown above.
}
else {
throw e2;
}
}
}
Is this a safe, correct, and equivalent replacement?
try (final AutoCloseable dummy = () -> context.close()) {
// use 'context' here
}
I think the answer is yes, but I want to confirm. I tried Googling for this pattern, but I found nothing. It is so simple! Thus, I am suspicious it may not be correct.
Edit: I just found this answer with a similar pattern.
final AutoCloseable dummy = context::close
– Unscrupulous