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

查看:290
本文介绍了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 如果捕获到异常?在此执行路径中没有返回语句。这是为什么编译器抱怨。

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 。如果将它定义为已检查的异常,则需要声明它抛出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天全站免登陆