I think the best thing to do is simply piggy-back off the try-with-resources
construct if you find that you have an AutoCloseable
, something like this:
/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
if (iterator instanceof AutoCloseable) {
try (AutoCloseable c = (AutoCloseable) iterator) {
return iterator.next();
}
} else {
return iterator.next();
}
}
Then the language-level construct will take care of exceptions (including in the close
method) in the correct way.