gpt4 book ai didi

java - 为什么 lambda 表达式的主体可以只由 throws 语句组成?

转载 作者:行者123 更新时间:2023-11-29 08:37:53 24 4
gpt4 key购买 nike

我有这个代码:

public class Sample {
public static void useCallable(Callable<Integer> expression){}

public static void main(String[] args){
useCallable(()->{throw new IOException();});
}
}

编译并运行良好。

但是,不应该Callable<Integer>不接受任何输入并返回一个整数?

()->{throw new IOException();}不返回任何内容,那么为什么它是有效的 Callable<Integer>表达?

最佳答案

出于同样的原因,此方法编译:

Integer foo() throws Exception {
throw new IOException();
}

出于与此方法相同的原因进行编译:

Integer foo() throws Exception {
if (hasFoo()) {
return getFoo();
} else {
throw new IOException();
}
}

引用JLS ,

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).

“正常完成”是什么意思?根据JLS (强调我的),

If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to complete normally. However, certain events may prevent a statement from completing normally:

  • The break (§14.15), continue (§14.16), and return (§14.17) statements cause a transfer of control that may prevent normal completion of statements that contain them.

  • Evaluation of certain expressions may throw exceptions from the Java Virtual Machine (§15.6). An explicit throw (§14.18) statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.

换句话说,具有返回类型的方法必须返回或抛出。你的是后者,所以它是有效的。

关于java - 为什么 lambda 表达式的主体可以只由 throws 语句组成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com