Java – how to add a throws exception clause when implementing a defined method in an interface without a throws clause?
I need a class to browse the collection, and then I implement the iterator interface
The only exception thrown by next () is NoSuchElementException, which means there are no more elements in the collection, which is not in line with my needs
Or should I not implement iterator at all?
Solution
To avoid this, if you need to add a checked exception, iterator. Is not implemented next. Iterator. Next doesn't throw any check exceptions, so basically iterator Next has a contract. There is nothing too bad and errors may occur. Users really need to consider it (objection, such as file. Open, you must worry about ioexceptions being thrown)
In view of this, I will consider the following options in the following order:
>Can I delete checked exceptions and replace them with unchecked exceptions? This will be my first attempt, because checked exceptions will cause some excitement every time they appear It's easy to solve your solution because your next () no longer throws checked exceptions If it's a third-party library, I can wrap it (which is a good idea anyway) and convert these exceptions to chked exceptions in the wrapper? > Can I wrap exceptions in runtime exceptions in iterators? There are constructors that can do this (constructors with throwable) This at least encapsulates what you use internally and allows you to use the iterator interface > can I replace the iterator with iteratable? If so, I can throw these checked exceptions during the creation of iteratable, and then the iterator will not throw exceptions This is only valid if the number of elements is small