为什么在System.exit(0)之后需要返回; [英] Why is return needed even after System.exit(0);

查看:144
本文介绍了为什么在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使用的编译器或解析器可以说明在执行 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)之后需要返回;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆