java - 有返回类型但没有 return 语句的函数正在编译。为什么?

标签 java

public String fun() {
        try {
            System.out.println("Hello World");
            throw new NullPointerException();
        } finally {
            System.out.println("Finally");
        }
    } 

为什么上面的函数编译时没有 return 语句?

最佳答案

Why does the above function compiles without return statement ?

因为方法的结尾无法到达 - 它总是会抛出NullPointerException

您应该将该规则视为“如果该方法具有非 void 返回类型,则每个正常返回(不抛出异常)的代码路径都必须返回一个值”。在本例中,没有这样的代码路径。

这在 JLS 8.4.7 中指定:

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

关于java - 有返回类型但没有 return 语句的函数正在编译。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669072/

相关文章:

java - Apache DBCP2 JCA 是否兼容?

java - 如何缩小 Vaadin 标签标题的字体大小?

java - 如何将 hashmap 的 arraylist 映射到另一个 hashmap arraylist

java - 从子类调用方法

java - Spring-Batch 没有将元数据持久化到数据库?

java - 寻找一种更简单的方法来让 ImmutableMultimap<String, String> 的 get 返回排序

java - Libgdx + 旋转 Sprite 点到触摸位置

java - 如何使用 FlywayDB 而不将数据库与生产转储对齐?

java - 如何通过 gradle 任务使用 spring 配置文件运行 bootRun

java - 如何继承静态字段并更改它的值?