In Java, how would you write an Iterable equivalent that could throw exceptions?

In java, a class can implement Iterable, which allows you to use the foreach () operator and iteration syntactic sugar:

for(T t:ts) ...

However, this does not allow you to throw construct exceptions for Iterator. If you were iterating over a network, file, database, etc., it would be nice to be able to throw exceptions. The obvious candidates are java.io.InputStream, Reader, and the java.nio.Channel code, but none of them can use Generics as the Iterable interface.

Is there a common idiom or Java API for this situation?

Clarification: this is the question of whether there is a template or an alternative interface for iterating objects outside the source without memory. As the respondents said, just throwing RuntimeExceptions to get around this problem is not recommended or what I was looking for.

Edit 2: Thanks for the answers. Consensus seems like you can't. May I extend the question to "What are you doing in this situation when this situation will be useful?" Just write your own interface?

+5
source share
5 answers

Sorry, you can’t. There are two problems:

  • The Iterator API does not throw any exceptions, so you will have to throw RuntimeExceptions (or non-Exception values)
  • for , .

. , # :

public static IEnumerable<string> ReadLines(string filename)
{
    using (TextReader reader = File.OpenText(filename))
    {
        string line;
        while ( (line=reader.ReadLine()) != null)
        {
            yield return line;
        }
    }
}

:

foreach (string line in ReadLines("foo.txt"))

foreach Dispose IEnumerator finally, ", - ( using)". , # , .

(!) - Java.

+4

, , . , a .

(, ) , , .

initialize, , .

try{
   ts.initializeIOIterator();
}catch(...)

for(T t:ts)
...    
+4

, , RuntimeIOException, hasNext/ .

try {
  for (...) {
    // do my stuff here
  }
catch (RuntimeIOException e) {
  throw e.getCause(); // rethrow IOException
}

RuntimeIOException , IOException:

class RuntimeIOException extends RuntimeException {
  RuntimeIOException(IOException e) {
    super(e);
  }

  IOException getCause() {
    return (IOException) super.getCause();
  }
}

.

+1

, , , , . , for, , .

, , .

0

, RuntimeException Iterable.

try - finally , foreach, , . Iterable, , .

, , , , (.. next()), next() false, next(). , , , next() , - ( false). , , .

, , Iterable. , , Iterable , "" (.. ), . , Iterable.

, ( " " ) - .

0

All Articles