Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should Iterator implementation deal with checked exceptions?

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");
    }
}
like image 374
amarillion Avatar asked Feb 27 '10 10:02

amarillion


1 Answers

I would wrap the checked exception in an unchecked exception, allowing it to be thrown without breaking Iterator.

I'd suggest an application specific exception extending RuntimeException, implementing the constructor (String, Throwable) so that you can retain access to the cause.

eg.

    @Override
    public boolean hasNext() {
      try {
        return !rs.isAfterLast();
      } catch (SQLException e) {
        throw new MyApplicationException("There was an error", e);
      }
    }

Update: To get started looking for more info, try Googling 'checked unchecked java sqlexception'. Quite a detailed discussion of of checked vs. unchecked exception handling on 'Best Practises for Exception Handling' on onjava.com and discussion with some different approaches on IBM Developerworks.

like image 194
brabster Avatar answered Oct 28 '22 13:10

brabster