Question

I've got the following method:

public T peek() throws StackEmptyException {
    Node<T> tracker = head; 
    while(tracker.getNext() != null) {
        tracker = tracker.getNext(); 
    }
    return tracker.getItem(); 
}

The problem is that when I try to do something like

int firstOne = stack.peek(); 

I get an unreported exception StackEmptyException and I have no idea what I'm doing wrong at this point. The StackEmptyException has been made in a separate class. Am I suppose to have this class extend that new exception class I made? So confused. Thoughts guys?

Was it helpful?

Solution 2

Checked exceptions (ie, a class which extends Exception but not RuntimeException or Error) thrown by a method should be handled by this method's caller, recursively so.

Here you have .peek() which throws, say, exception class E (bad name, but this is for illustration). You must do one of the following in a foo() method which calls .peek():

  • catch it, or
  • throw it again.

That is, either:

// catch
void foo()
{
    try {
        peek();
    } catch (E e) {
       // something
    }
}

or:

// throw
void foo() throws E
{
    peek();
}

You could even rethrow it:

// catch then rethrow
void foo() throws E
{
    try {
        peek();
    } catch (E e) {
        // something, then
        throw e;
    }
}

OTHER TIPS

Since StackEmptyException is an checked exception (which you shouldn't do in first place), you should handle that exception when invoking the peek() method. The rule is, either you should handle the exception or declare it to be thrown.

However, I would take a step back and change StackEmptyException to an Unchecked Exception. Then you wouldn't need to handle it or declare it as thrown.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top