Java Compiler Error: Missing Return Statement

Java Compiler Error: Missing Return Statement

所以我收到编译器错误,我缺少 return 语句,我已经查看了其他类似的问题,但我仍然对此事感到困惑。

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!");
  }
}

如果之前有人问过这个问题,我提前表示歉意,但我已经看过其他各种问题,但我似乎无法弄清楚。

如果捕获到异常,pop的return值是多少?此执行路径中没有 return 语句。这就是编译器抱怨的原因。

在这种情况下,pop 的调用者需要处理 EmptyStackException。不要在 pop 方法中捕获 EmptyStackException。如果您将其定义为检查异常,则需要声明它 throws EmptyStackException。如果你不捕获它,那么该方法将始终 return 值或抛出异常,这将满足编译器。

请注意,可以在 catch 块之后 return 一个值。这也会让编译器满意,但你会 return 什么?无效的?然后调用者必须测试 null,但调用者也可以捕获 EmptyStackException.

您的问题全在于范围界定

当您的函数运行时,它会经历两个条件

  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

如何解决:

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