How to create a Java Iterator that throws IOException

ioexception, iterator, java, java-7

Solution

It isn't exactly what you want, but consider:

This is happening over a network, so it may be slow. You should be probably be using a `Future` (or similar).

So, instead of having your `RemoteIterator<E>` where `next()` returns a E, use

`RemoteIterator<Future<E>>`, where it returns a `Future<E>`.

In the `Future.get()` method, you can wrap any `IOException` in an `ExecutionException`.

Not perfect, but `Future.get()` implies that things may be slow, plus it does throw a checked exception which will tip off other programmers what is happening, and the natural response is to call `getCause()`. So this avoids most of the "WTF" aspects.

Problem

I'd like to implement an iterator that retrieves objects from disk/network. ``` Iterator itr = getRemoteIterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } ``` However the problem is that `hasNext()` and `next()` methods of the Iterator object does not allow to throw `IOException`. Is there any other standard interface work around this issue? Desired code is: ``` public interface RemoteIterator<E> { boolean hasNext() throws IOException; E next() throws IOException; void remove(); } ```

Original source