为什么即使在 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.
相关文章