Search code examples
javagenericscustom-exceptions

Java Error: Unreported exception?


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?


Solution

  • 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;
        }
    }