How to add throws to an Exception clause when implementing a method defined in the interface without throwing clauses?

I need a class to navigate the collection, then I implemented the Iterator interface. But the problem is that my implementation of the next () method should throw an exception, because the members of the collection must be generated dynamically, and exceptions can occur during the generation process.

The only throw by next () exception is a NoSuchElementException, which means that the collection no longer has an element, and this does not meet my need.

Or should I not implement Iterator at all?

+3
source share
3 answers

To be pedantic, you do not implement Iterator.next if you need to add a checked exception. Iterator.next does not throw excepted exceptions, so basically Iterator.next has a contract that nothing bad can go the way the user really should think (against, say, File.open, where you need to worry about what IOExceptions will get throw).

Given this, I would consider the following options in the following order:

  • Can I remove checked exceptions and replace them with unchecked exceptions? This would be my first attempt, because the checked exceptions cause some annoyance every time they appear. This will easily resolve your solution, because then your next () will no longer throw checked exceptions. If this is a third-party library, can I wrap it (which would be a good idea, anyway) and turn these exceptions into excluded exceptions in the shell?

  • Can I wrap exceptions from runtime exceptions in an iterator? There are constructors for this (those who have Throwable). This at least encapsulates what you use internally and allows you to use the Iterator interface

  • Can I replace Iterator with Iterable? If so, I can throw these checked exceptions during Iterable creation, and then the iterator cannot throw exceptions. This will only work if the number of elements is not large.

+5
source

Your iterator may RuntimeException subclass of RuntimeException . This does not need to be declared in the method signature.

Note that NoSuchElementException also a subclass of RuntimeException , and is also not declared in the signature of the Iterator.next() method (it is only mentioned in javadoc).

+1
source

Well, you cannot implement java.util.Iterator by default if your exception is a checked exception. One solution might be to extend the java.lang.RuntimeException and therefore avoid declaring an exception in the method signature.

+1
source

Source: https://habr.com/ru/post/1392795/


All Articles