开发者

How should Iterator implementation deal with checked exceptions?

开发者 https://www.devze.com 2022-12-21 05:22 出处:网络
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?

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()开发者_Python百科
    {
        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");
    }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号