So I'm getting the compiler error that I'm missing a return statement and I have looked at the other similar questions but I'm still confused about this matter.
public String pop()
{
try
{
if(top == -1)
{
throw new EmptyStackException("The stack is empty!");
}
String x = stack[top];
top--;
return x;
}
catch (EmptyStackException e)
{
System.out.println("The stack is empty!");
}
}
I apologize in advance if this question has been asked before but I have looked at various others and I cannot seem to figure this out.
Your Problem is all about scoping
When your function runs it goes through two conditions
How to resolve it:
What is the return value of
pop
if the exception is caught? There is no return statement in this execution path. That is why the compiler is complaining.In this case, the caller of
pop
needs to handle theEmptyStackException
. Don't catchEmptyStackException
inside thepop
method. You'll need to declare that itthrows EmptyStackException
if you defined it to be a checked exception. If you don't catch it, then the method will always return the value or throw the exception, and that will satisfy the compiler.Note that it's possible to return a value after the
catch
block. This will also satisfy the compiler, but what would you return? Null? Then the caller must test fornull
, but the caller might as well catch theEmptyStackException
.