Ben Joshua S Ben Joshua S - 5 months ago 25
Java Question

How to throw a StackOverflowException

I am currently making a Bounded Array Stack. this method throws arrays that are larger then the storage capacity to the

StackOverflowException
, except i keep getting an error message for the "
throws StackOverflowException
part

public void push(T item) throws StackOverflowException {
//push item onto the stack,
if (isFull()) throw new StackOverflowException();
else {
top++;
storage[top] = item;
}
}


Error Message:


Error:(52, 17) java:
push(T)
in
com.ld.BoundedArrayStack
cannot
implement
push(T)
in
com.ld.StackADT
overridden method does not throw
com.ld.StackOverflowException



other message:


push(T)
in
com.Id.BoundedArrayStack
clashes with
push(T)
in
com.Id.StackADT
; overridden method does not throw
com.Id.StackOverflowException



i dont understand what the problem is.

Answer

From your error message, your superclass StackADT defined push not to throw StackOverflowException, so any override of this method cannot throw StackOverflowException either.

You can either:

  • Make your StackOverflowException a RuntimeException, which can always be thrown at any time. You don't have to declare it in the throws clause, or
  • Declare the push method in StackADT so that it throws a StackOverflowException.