开发者

How to add throws Exception clause when implementing a method defined in a interface without throws clause?

I need a class to navigate across a collection, then I implemented Iterator interface. But the problem is, my implementation of next() method need to throw an Exception, because the collection members need to be generated dynamically, and Exceptions may happen during the generating process.

The only exception throws by next() is NoSuchElementException which means no more element in the colle开发者_如何转开发ction, and this does not meet my need.

Or, I should not implement Iterator at all?


To be pedantic, you are not implementing Iterator.next if you need to add a checked exception. Iterator.next throws no checked exceptions, so basically Iterator.next has the contract that nothing too bad can go wrong the user really needs to think about (opposed to, say, File.open where you have to worry about IOExceptions getting thrown).

Given that, I'd consider the following options, in that order:

  • Can I remove the checked exceptions and replace them with unchecked exceptions? This would be my first try, because checked exceptions are causing quite some stir-up everytime they appear. This would easily solve your solution, because then your next() does not throw checked exceptions anymore. If it is a third party library, could I wrap it (Which would be a good idea, anyway) and turn these exceptions into chcked exceptions in the wrapper?

  • Can I wrap the exceptions in a runtime exception in the iterator? There are constructors to do this (those with a Throwable). This would at least encapsulate what you use internally and allow you to use the Iterator-interface

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


Your iterator can throw a subclass of RuntimeException. This doesn't need to be declared in the method signature.

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜