Exception handling in Iterable

Posted by Maas on Stack Overflow See other posts from Stack Overflow or by Maas
Published on 2010-06-01T04:54:43Z Indexed on 2010/06/01 5:03 UTC
Read the original article Hit count: 235

Filed under:
|
|

Is there any way of handling -- and continuing from -- an exception in an iterator while maintaining the foreach syntactic sugar?

I've got a parser that iterates over lines in a file, handing back a class-per-line. Occasionally lines will be syntactically bogus, but that doesn't necessarily mean that we shouldn't keep reading the file.

My parser implements Iterable, but dealing with the potential exceptions means writing

for (Iterator iter = myParser.iterator(); iter.hasNext(); ) {
  try {
    MyClass myClass = iter.next();
    // .. do stuff ..
  } catch (Exception e) {
    // .. do exception stuff ..
  }
}

.. nothing wrong with that, but is there any way of getting exception handling on the implicit individual iter.next() calls in the foreach construct?

© Stack Overflow or respective owner

Related posts about java

Related posts about exception