as described in the title, I am trying to design an iterator over some data, which might fail somewhere down the line. An example would be an Iterator<DatabaseObject> that would, upon the call to next() read in the next row from DB and proceed. Other examples might include processing data using objects from API that raise Exception. The question is how to respond in this scenario, as Iterator is not allowed to raise any exceptions… Should we throw NoSUchElementException and provide meaningful message there?
as described in the title, I am trying to design an iterator over some
Share
You can throw an unchecked exception. It makes sense to throw
NoSuchElementException, since, in fact, an error prevented there from being such an element.It would be nice if the exception would wrap any underlying exception. Unfortunately,
NoSuchElementExceptiondoes not have a constructor that takes another exception. So if you want to propagate the underlying cause up, you’ll have to go a different route, such as throwing aRuntimeException:Alternatively, you could return some reserved value (such as
null).