title: What to do of exceptions when implementing java.lang.Iterator
body: <p>The <a href="http://java.sun.com/javase/6/docs/api/java/util/Iterator.html" rel="noreferrer"><code>java.lang.Iterator</code></a> interface has 3 methods: <code>hasNext</code>, <code>next</code> and <code>remove</code>. In order to implement a read-only iterator, you have to provide an implementation for 2 of those: <code>hasNext</code> and <code>next</code>.</p>
  
  <p>My problem is that these methods does not declare any exceptions. So if my code inside the iteration process declares exceptions, I must enclose my iteration code inside a try/catch block.</p>
  
  <p>My current policy has been to rethrow the exception enclosed in a <code>RuntimeException</code>. But this has issues because the checked exceptions are lost and the client code no longer can catch those exceptions explicitly.</p>
  
  <p>How can I work around this limitation in the Iterator class?</p>
  
  <p>Here is a sample code for clarity:</p>
  
  <pre><code>class MyIterator implements Iterator
  {
      @Override
      public boolean hasNext()
      {
          try
          {
              return implementation.testForNext();
          }
          catch ( SomethingBadException e ) 
          {
              throw new RuntimeException(e);
          }
      }
  
      @Override
      public boolean next()
      {
          try
          {
              return implementation.getNext();
          }
  
          catch ( SomethingBadException e ) 
          {
              throw new RuntimeException(e);
          }
      }
  
      ...
  }
  </code></pre>