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?
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, NoSuchElementException does 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 a RuntimeException:
try {
...
} catch (<some exception type> e) {
throw new RuntimeException("Next element not accessible", e);
}
Alternatively, you could return some reserved value (such as null).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With