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) 之后也需要返回;
基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01