What is an appropriate way to programmatically exit an application?

后端 未结 6 1568
慢半拍i
慢半拍i 2021-01-26 17:57

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 terminate

6条回答
  •  梦毁少年i
    2021-01-26 18:31

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

提交回复
热议问题