3

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.

4
  • 6
    What's confusing? What does your method return if you hit an exception and your catch statement catches it? Commented Mar 27, 2015 at 22:03
  • what will happen if everything go wrong and you to catch block? Commented Mar 27, 2015 at 22:04
  • there needs to be a return statement either in the catch block or after the catch block Commented Mar 27, 2015 at 22:05
  • 1
    I understand the mistake I made now, thank you. Commented Mar 27, 2015 at 22:10

2 Answers 2

3

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 the EmptyStackException. Don't catch EmptyStackException inside the pop method. You'll need to declare that it throws 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 for null, but the caller might as well catch the EmptyStackException.

Sign up to request clarification or add additional context in comments.

Comments

-1

Your Problem is all about scoping

When your function runs it goes through two conditions

  1. if everything goes well which is gonna be tr block so it will return String

Your issue is in condition two:

  1. if everything does not go well which is gonna be catch block which you do not return any String type and in your function looks for a String type to return to caller but it cannot find so you got an error

How to resolve it:

Simply return an empty String to indicate something has gone wrong.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.