Java基础——方法中返回类型和返回语句的一些混淆 [英] Java fundamental - a little confusion on return type and return statement in methods

查看:50
本文介绍了Java基础——方法中返回类型和返回语句的一些混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My understanding is that in Java if a method declare a return type, compilation fails if we don't put a return statement in the method. But the following code compiles successfully.

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

现在有点糊涂了.我觉得我的理解是错误的.有人可以澄清吗?谢谢.

Now I am a little confused. I think my understanding is wrong. Can someone please clarify? Thank you.

推荐答案

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

A Java method must either return, or throw an exception. The compiler refuses to compile if all the possible code paths don't lead to either a return or an exception. The unique code path in this method throws an exception, so it's valid.

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

What would be invalid would be this, because if i <= 0, nothing is returned, and no exception is thrown:

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;
    }
}

这篇关于Java基础——方法中返回类型和返回语句的一些混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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