views:

364

answers:

6

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");
    }
}
+3  A: 

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.

Dmitry
Yeah, System.exit(0) is just fine for what you described. Dmitry's suggestion to return to main() is a good idea, though, in case you expand the program in the future and open stuff that needs releasing.
Jeff
Would you mind giving a quick example on returning to main() and exiting from there? -- Thank you
denchr
I've edited my answer
Dmitry
A: 

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.

Secko
+1  A: 

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.

Loadmaster
The code in my example is within main. I think have some trouble figuring out the meaning of "Returning all the way back to main()". Sorry, that's why I asked for an example in the previous answer.
denchr
Sorry. Other than using `System.exit()`, flowing *out of* `main()` is the cleanest way.
Loadmaster
+2  A: 

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.

tylerl
A: 

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
}
A: 

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.

Brian Agnew