Why is return needed even after System.exit(0);(为什么即使在 System.exit(0) 之后也需要返回;)
问题描述
考虑这个函数:
public boolean foo(){
System.exit(1);
//The lines beyond this will not be read
int bar = 1; //L1
//But the return statement is required for syntactically correct code
return false; //L2
//error here for unreachable code
//int unreachable = 3; //L3
}
谁能解释一下为什么 L1 和 L2 明显不可访问不会发出警告,而 L3 会发出警告.
Can someone please explain why L1 and L2 visibly not reachable does not give warnings but L3 does.
推荐答案
因为对于编译器而言,System.exit()
只是另外一个方法调用.
Because as far as the compiler is concerned, System.exit()
is just another method call.
它所做的是结束进程的事实只能从实现中找到(这是本机代码,而不是它有任何区别).
The fact that what it does is end the process can only be found out from the implementation (which is native code, not that it makes any difference).
如果你必须把 System.exit()
放在你的代码中(通常最好避免它,除非你想返回一个不是 0 的代码),它真的应该放在一个方法中例如,返回 void
、main()
.这样更好.
If you have to put System.exit()
in your code (usually it's best to avoid it, unless you want to return a code other than 0), it should really be in a method that returns void
, main()
for example. It's nicer that way.
关于可达性,解释是一样的:return
是Java语言的一个关键字,所以IDE使用的编译器或者解析器可以判断出<后面的代码理论上是不可能的code>return 要执行的语句.这些规则在这里定义.
As for the reachability, the explanation is the same: return
is a keyword of the Java language, so the compiler or the parser the IDE uses can tell that it's theoretically impossible for code after the return
statement to be executed. These rules are defined here.
这篇关于为什么即使在 System.exit(0) 之后也需要返回;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么即使在 System.exit(0) 之后也需要返回;


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01