Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
731 views
in Technique[技术] by (71.8m points)

exception handling - Java Compiler Error: Missing Return Statement

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...