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/