How should Iterator implementation deal with checked exceptions?

百般思念 提交于 2019-12-05 22:04:34

问题


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");
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/2346978/how-should-iterator-implementation-deal-with-checked-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!