What is an appropriate way to programmatically exi

2019-03-04 08:06发布

问题:

I am evaluating user inputs as commands for my application. If the user presses Q, or q, and then hits enter, the application quits and execution terminates.

Is there a proper context, or best practices on how to do that? I do not have any resources to release, or anything like that. Should I just use System.exit(0);? Is there a recommended way to do that?

As my first approach I do something like this:

while (true){
    try{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //Other logic goes here...
        if (br.readLine().equalsIgnoreCase("Q")){
            System.exit(0);
        }
    }
    catch (IOException ioe) {
        System.out.println("IO error trying to read your selection");
    }
}

回答1:

You might as well return up to main() and return from there.

    private void loop() {
        while (true){
           try{
               BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

               //other logic goes here...
               if(br.readLine().equalsIgnoreCase("Q")){
                   return; // You're done and you are returning to the caller.
               }
           }
           catch (IOException ioe) {
               System.out.println("IO error trying to read your selection");
           }
        }
    }

    public static void main(String[] args) {
        loop();
    }

But if you don't have anything to release, System.exit(0) is fine.



回答2:

Resources are cleaned up automatically by the OS when the process exits. There are two primary reasons to not just exit() from the middle of the code (this applies to all languages).

  • There may be some action that needs to be taken before the program ends. For example, you may need to save any open files (i.e. write changes that for performance or other reasons have not been sent to the file yet).

  • Someone may want to later use your code for some other purpose.

Take for example, the Git version control system. There's several efforts to turn the code into a library instead of a set of stand-alone executables so that it can be efficiently incorporated into other projects. One of the problems (from what I've heared) is that the code sometimes simply terminates instead of tracking and cleaning up the resources it's using. As an executable that's fine, but if it was imported as a library, you don't always want to just terminate the host application because you've finished your little part.



回答3:

Returning all the way back to Returning out of main() is the cleanest way, of course, but if that's not easy to do, System.exit() is perfectly fine.

It's not directly relevant to your question, but throwing an (unhandled) exception is usually the way to terminate on a fatal condition, since it provides a lot of tracing info to the poor user.



回答4:

I would like to say:

It doesn't matter, it's entirely up to you!

And dough it sometimes is true, other times it depends on the program structure and code integrity.

The reasonable exit would be through main method, terminating all the threads.

System.exit forces termination of all the threads in the JVM. The System.exit never returns normally. It should be used for an error.



回答5:

System.exit() is fine. And I agree with the other answers, returning to main would be the best way to exit - from a maintenance point of view. As your code expands you may forget the little method doing System.exit have to debug to remember it.

However you only need to use exit if you have a script which needs the information about an abnormal termination. Otherwise there is no need.

As I recall a Java program will exit with 0 by default - meaning normal termination. So you'd want to use System.exit(n) for cases where your program terminates due to some error.

Example (just using static methods you'd most likely want to instantiate...):

public static void main(String[] args) {
   try {
     doStuff();
   } catch (SomeRuntimeException e) {
     // marching orders! Exit with errorcode
     <log the error with sufficient info for debugging>
     System.exit(1);
   }
}

private static doStuff() {
  // doing my thing ...
  ...
  //then some error occurs and I have no other choice but to do a hard exit
  throw new SomeRuntimeException(  ... some info would be nice ...)
  ...
  return
}


回答6:

Don't forget that if you perform a System.exit(), you can't easily later use your methods in a standalone library. If you want to reuse your code outside your existing solution (and you may not now, but decide to do so in the future), then you'll then have to revisit and refactor appropriately.

Otherwise the worst-case scenario is that you take the existing code without noticing the System.exit()s, use it and then have your library exit unexpectedly in a new application.

Just something to bear in mind re. code-reuse.