In java a class can implement Iterable which lets you use the foreach() statement and the iteration syntatic sugar:
for(T t:ts) ...
However, this does not allow you to throw exceptions on the construction for an Iterator. If you were iterating off a network, file, database etc it would be nice to be able to throw exceptions. Obvious candidates are java.io.InputStream, Reader and the java.nio.Channel code, but none of this can use Generics like the Iterable interface can.
Is there a common idiom or Java API for this situation?
Clarification: This is asking if there is a pattern or alternative interface for iterating for objects off a non-memory source. As responders have said, just throwing RuntimeExceptions to get around the problem is not recommended or what I was looking for.
Edit 2: Thanks to answers so far. The consensus seems to be ‘you can’t’. So can I extend the question to ‘What do you do in this situation, when this situation would be useful?’ Just write your own interface?
Unfortunately you can’t. There are two problems:
This is very annoying. In C#, for instance, you can really easily write code to iterate through the lines of a text file:
Use as:
The foreach loop calls
Disposeon theIEnumeratorin a finally block, which translates to ‘check if we need to do anything in the iterator block’s finally (from the using statement)’. Obviously there are no checked exceptions in C#, so that side of things isn’t a problem either.A whole (useful!) idiom is pretty much unworkable in Java due to this.