1

I am trying to implement a stack with some functions in Java. I have created the class UnderflowException that implements Exception like this:

package exceptions;

public class UnderflowException extends Exception
{
    public UnderflowException(String err)
    {
        super(err);
    }
}

When I'm implementing the Interface I get the following error "No exception of type UnderflowException can be thrown; an exception type must be a class of Throwable" when I try to throw.

My interface looks like this:

import exceptions.*;
public interface Stack
{
    public void push(Object x);
    public void pop() throws UnderflowException;
    public Object top() throws UnderflowException;
    //other functions
}

Is there a problem with the UnderflowException class? Thank you!

Stefan
  • 83
  • 1
  • 6
  • 20
  • 5
    Are you extending `java.lang.Exception` or some custom `Exception` class? – JonK Oct 21 '14 at 07:47
  • I believe it's `java.lang.Exception`. – Stefan Oct 21 '14 at 08:28
  • 1
    That error message suggests that `Throwable` isn't in the type hierarchy of your `UnderflowException` class - which it definitely would be if you were extending `java.lang.Exception`. If there is a class called `Exception` in your exceptions package then you may be inadvertently inheriting from it. – JonK Oct 21 '14 at 08:32

1 Answers1

2

Replace Exception with java.lang.Exception. Looks like you use wrong class and FQN help solve problem.

talex
  • 17,973
  • 3
  • 29
  • 66
  • I've replaced `Exception` with `java.lang.Exception` and now seems to work. Thank you! – Stefan Oct 21 '14 at 08:39
  • 1
    Look at your imports. Or maybe you have your own `Exception` class in this package. (Call you own class `Exception` is bad idea because it cause lots of misunderstandings) – talex Oct 21 '14 at 13:15