Java 编译器错误:缺少返回语句 [英] Java Compiler Error: Missing Return Statement

查看:36
本文介绍了Java 编译器错误:缺少返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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.

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

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.

请注意,可以在 catch 块之后返回一个值.这也将满足编译器,但你会返回什么?空值?然后调用者必须测试 null,但调用者也可以捕获 EmptyStackException.

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.

这篇关于Java 编译器错误:缺少返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆