【问题标题】:Java fundamental - a little confusion on return type and return statement in methodsJava 基础 - 方法中的返回类型和返回语句有点混乱
【发布时间】:2012-01-07 10:22:45
【问题描述】:

我的理解是,在Java中,如果一个方法声明了一个返回类型,如果我们不在方法中放置一个return语句,编译就会失败。但是下面的代码编译成功。

 public int test() throws Exception{
        throw new Exception("exception");
    }

现在我有点困惑。我认为我的理解是错误的。有人可以澄清一下吗? 谢谢。

【问题讨论】:

    标签: java return


    【解决方案1】:

    Java 方法必须要么返回,要么抛出异常。如果所有可能的代码路径都没有导致返回或异常,编译器将拒绝编译。该方法中唯一的代码路径会抛出异常,所以是有效的。

    无效的是这个,因为如果i <= 0,什么都不返回,也不抛出异常:

    public int test() throws Exception {
        int i = new Random().nextInt();
        if (i > 0) { 
            throw new Exception("exception");
        }
    }
    

    改为有效

    public int test() throws Exception {
        int i = new Random().nextInt();
        if (i > 0) { 
            throw new Exception("exception");
        }
        else {
            return 0;
        }
    }
    

    【讨论】:

    • 我要补充一点,这是返回值的正常方式。 Excelption 是一种不同的机制来处理可能发生的错误。两者不相等,不应使用异常机制代替 return 来提供一种将值传达给调用者的额外方式。
    猜你喜欢
    • 2015-03-18
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    相关资源
    最近更新 更多