开发者

Difficulty throwing NoSuchElementException in Java

this is my first attempt to a code doubly linked program in java:

This is my implementation of getting an iterator to getall items in the doubly linkedlist

public Object next()  {
    if(list.getSize()==0){
     throw new NoSuchElementException();

    }else{ 
        current=current.getNext();
        return current.getItem();
    } 
}

Please dont laugh at me but whatever I try I am getting

Cannot find symbol : symbol class: NoSuchElementException

I tried creating a class NoSuchElementException.java which extends Exception

Then I get

unreported exception NoSuchElementException; must be caught or declared to be thrown throw new NoSuchElementException();

I tried changing code to :

public Object next() throws NoSuchElementException {

The开发者_StackOverflown I get

next() in ElementsIterator cannot implement next() in java.util.Iterator; overridden method does not throw NoSuchElementException

Can anybody point to where I got wrong. If this is not sufficient info to resolve this issue, please do tell me.


You need to import java.util.NoSuchElementException instead of creating your own.


The compiler is giving you a pretty good explanation. You are providing an implementation of the next() method declared in Iterator, which has a signature of:

public Object next()

However, you have introduced your own checked exception called NoSuchElementException, which required that you change the method signature to:

public Object next() throws NoSuchElementException

Now you are no longer implementing the method declared in the interface. You've changed the signature.

Anyways, there are a couple ways you can fix this:

  1. Change your NoSuchElementException class so that it inherits from RuntimeException instead of just Exception. Then you don't need to add a throws declaration to the method signature.

  2. Get rid of your custom exception type and instead use Java's built-in NoSuchElementException, which already inherits from RuntimeException. This is almost certainly the better option.


The next() method of Iterator does not declare an exception to be thrown, so you can't decalre an exception if you are implementing it.

You can however throw an unchecked exception. The simple fix is to define your custom exception as extends RuntimeException, which will make it an unchecked exception.

I'm a little confused, because NoSuchElementException is an unchecked exception already, unless you have defined your own NoSuchElementException class.


Check the javadocs for java.util.Iterator and java.util.NoSuchElementException. If you implement the Iterator interface, you have to play by its rules. Import that exception; don't create it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜