java 退出方法的最佳方式是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16255267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Which is the Best way to exit a method
提问by RajaSekar
I was looking for the ways to exit a method, i found two methods System.exit(); Return;
我正在寻找退出方法的方法,我找到了两种方法 System.exit(); 返回;
System.exit() - Exits the full program Return exits current method and returns an error that remaining code are unreachable.
System.exit() - 退出完整程序 Return 退出当前方法并返回剩余代码无法访问的错误。
class myclass
{
public static void myfunc()
{
return;
System.out.println("Function ");
}
}
public class method_test
{
public static void main(String args[])
{
myclass mc= new myclass();
mc.myfunc();
System.out.println("Main");
}
}
回答by Suresh Atta
The best and proper way to exit from method is adding return statement
.
退出方法的最佳和正确方法是添加return statement
.
System.exit()will shutdown your programm.
System.exit()将关闭您的程序。
if you use system.exit
once a thread goes there, it won't come back.
如果您使用system.exit
一次线程到达那里,它就不会回来。
system.exit is part of Design of the Shutdown Hooks API
system.exit 是Shutdown Hooks API 设计的一部分
回答by Dmitry
There is no best way, it depends on situation.
没有最好的方法,这取决于情况。
Ideally, there is no need to exit at all, it will just return.
理想情况下,根本不需要退出,它只会返回。
int a() {
return 2;
}
If there is a real need to exit, use return, there are no penalties for doing so.
如果确实需要退出,请使用 return,这样做不会受到任何惩罚。
void insertElementIntoStructure(Element e, Structure s) {
if (s.contains(e)) {
return; // redundant work;
}
insert(s, e); // insert the element
}
this is best avoided as much as possible as this is impossible to test for failure in voids
最好尽可能避免这种情况,因为这是不可能测试空洞故障的
Avoid system.exit in functions, it is a major side effect that should be left to be used only in main.
避免在函数中使用 system.exit,这是一个主要的副作用,应该只在 main 中使用。
void not_a_nice_function() {
if (errorDetected()) {
System.exit(-1);
}
print("hello, world!");
}
this pseudocode is evil because if you try to reuse this code, it will be hard to find what made it exit prematurely.
此伪代码是邪恶的,因为如果您尝试重用此代码,将很难找到导致它过早退出的原因。
回答by Junaid Hassan
first of all your code will kill good programmers imagine this code Which is the Best way to exit a methodthis code example that how a return comes before a System.out.print(); as it becomes unreachable after the return statement lols the command
首先你的代码会杀死优秀的程序员想象这段代码这是退出方法的最佳方式这个代码示例返回如何在 System.out.print() 之前出现;因为在 return 语句大声笑命令后变得无法访问
System.exit(int status); (status=0 for Normal Exit && status=-1 for abnormal exit
is only used if you want to exactly quit your whole app whereas the command
仅在您想完全退出整个应用程序时使用,而命令
return;
is used to get out/return from a method these two are different in their operations
用于从方法中退出/返回这两者的操作不同