Unfortunately, you cannot do this. Exclusions are part of the method signature, and although you can narrow them down, for example.
interface FooCallable extends Callable<T> { T call() throws IOException;
you cannot enter new throw offers or extend the declared one.
Iterator is the fundamental Java interface used by advanced for, so even if you can somehow do what you need, the compiler needs to know that
for (T obj: ioExceptionThrowingIterable) { ... }
it is required that a validated IOException be caught or thrown.
This is a matter of opinion, but I think you should use your own RuntimeException subclass and carefully document your interface. Verified exceptions are excluded in the modern framework, for example. Spring, due to problems associated with them.
Edit : borrowed and adapted from user949300 answer, you can wrap the returned object, for example,
interface RemoteObject<T> { T get() throws IOException }
Then return Iterator<RemoteObject<T>> and force the caller to handle the IOException when deploying with get :
for (RemoteObject<Foo> obj: iterable) { try { foo = obj.get() } catch (IOException ex) { } }
In this case, there is no need to extend Iterator , it can be used directly. In fact, you can use Collection , if applicable.
artbristol
source share