I'm wrapping a java.sql.RecordSet inside a java.util.Iterator. My question is, what should I do in case any recordset method throws an SQLException?
The java.util.Iterator javadoc explains which exceptions to throw in various situations (i.e. NoSuchElementException in case you call next() beyond the last element)
However, it doesn't mention what to do when there is an entirely unrelated problem caused by e.g. network or disk IO problems.
Simply throwing SQLException in next() and hasNext() is not possible because it is incompatible with the Iterator interface.
Here is my current code (simplified):
public class MyRecordIterator implements Iterator<Record>
{
private final ResultSet rs;
public MyRecordIterator() throws SQLException
{
rs = getConnection().createStatement().executeQuery(
"SELECT * FROM table");
}
@Override
public boolean hasNext()
{
try
{
return !rs.isAfterLast();
}
catch (SQLException e)
{
// ignore, hasNext() can't throw SQLException
}
}
@Override
public Record next()
{
try
{
if (rs.isAfterLast()) throw new NoSuchElementException();
rs.next();
Record result = new Record (rs.getString("column 1"), rs.getString("column 2")));
return result;
}
catch (SQLException e)
{
// ignore, next() can't throw SQLException
}
}
@Override
public void remove()
{
throw new UnsupportedOperationException("Iterator is read-only");
}
}