With some frequency, I find myself writing APIs that offer Iterator<Foo> , which is supported by a network connection. The implementation opens a network connection, reads information from the stream, and deserializes this information in Foo to pass to the caller. Unfortunately, there is always the possibility of an IOException , as well as the need to correctly close the network connection (which can be done automatically when the caller reads the last Foo , but what if this does not happen?).
There are already a couple of questions ( here and here ) on how to deal with checked exceptions that will be implemented in the Iterator implementation, and the accepted advice is "to wrap them in an unverified RuntimeException s". Meanwhile, to allow the closure of the network connection, we can implement Closeable . So, we got something like this for a good user checking exception checking:
Iterator<Foo> iter = null; try { iter = getFooIterator(); while(iter.hasNext()) { Foo foo = iter.next(); // do something with foo } } catch(RuntimeException e) { if(e.getCause() instanceof IOException) { // do something with the IOException } else throw e; } finally { if(iter instanceof Closeable) try { ((Closeable)iter).close(); } catch(IOException e) {} }
And it seemed like such a good idea to implement Iterator . Is there a better way?
source share