Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

java - Which is the Best way to exit a method

I was looking for the ways to exit a method, i found two methods 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");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...