这是退出方法的最佳方法 [英] Which is the Best way to exit a method
问题描述
我一直在寻找退出方法的方法, 我发现了两种方法 System.exit(); 返回;
I was looking for the ways to exit a method, i found two methods System.exit(); Return;
System.exit()-退出完整程序 Return退出当前方法,并返回一个错误,指出剩余代码无法访问.
System.exit() - Exits the full program Return exits current method and returns an error that remaining code are unreachable.
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");
}
}
推荐答案
没有最好的方法,这取决于具体情况.
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;
}
如果确实需要退出,请使用return,这样做没有任何惩罚.
If there is a real need to exit, use return, there are no penalties for doing so.
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
避免在函数中使用system.exit,这是主要的副作用,应仅在main中使用.
Avoid system.exit in functions, it is a major side effect that should be left to be used only in 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.
这篇关于这是退出方法的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!