为什么即使在 System.exit(0) 之后也需要返回;

Why is return needed even after System.exit(0);(为什么即使在 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 的代码),它真的应该放在一个方法中例如,返回 voidmain().这样更好.

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) 之后也需要返回;

基础教程推荐