Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...