以编程方式退出应用程序的适当方法是什么?

发布于 2024-08-11 19:30:21 字数 568 浏览 12 评论 0原文

我正在评估用户输入作为我的应用程序的命令。如果用户按 Qq,然后按 Enter,应用程序将退出并终止执行。

是否有适当的背景或最佳实践来说明如何做到这一点?我没有任何资源可以释放,或者类似的东西。我应该只使用 System.exit(0); 吗?有推荐的方法吗?

作为我的第一种方法,我做了这样的事情:

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");
    }
}

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");
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

亽野灬性zι浪 2024-08-18 19:30:21

您不妨返回到 main() 并从那里返回。

    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();
    }

但如果您没有任何要释放的内容,System.exit(0) 就可以了。

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.

假装爱人 2024-08-18 19:30:21

当进程退出时,操作系统会自动清理资源。不只是从代码中间退出()有两个主要原因(这适用于所有语言)。

  • 在程序结束之前可能需要采取一些操作。例如,您可能需要保存任何打开的文件(即,出于性能或其他原因尚未发送到文件的写入更改)。

  • 稍后有人可能想将您的代码用于其他目的。

以 Git 版本控制系统为例。人们做出了一些努力将代码转换为库而不是一组独立的可执行文件,以便可以有效地将其合并到其他项目中。问题之一(据我所知)是代码有时只是终止,而不是跟踪和清理它正在使用的资源。作为可执行文件没问题,但如果它作为库导入,您并不总是希望终止主机应用程序,因为您已经完成了您的小部分。

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.

苏别ゝ 2024-08-18 19:30:21

一路返回 当然,从 main() 返回是最干净的方法,但如果这不容易做到,System.exit() 完全没问题。

它与您的问题没有直接关系,但抛出(未处理的)异常通常是在致命情况下终止的方法,因为它为可怜的用户提供了大量跟踪信息。

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.

稍尽春風 2024-08-18 19:30:21

我想说:

没关系,完全取决于
你!

有时它是正确的,有时它取决于程序结构和代码完整性。

合理的退出是通过 main 方法终止所有线程。

System.exit 强制终止 JVM 中的所有线程。 System.exit 永远不会正常返回。它应该用于错误。

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.

葬心 2024-08-18 19:30:21

System.exit() 没问题。我同意其他答案,从维护的角度来看,返回主将是退出的最佳方式。随着代码的扩展,您可能会忘记执行 System.exit 的小方法,必须调试才能记住它。

但是,只有当您的脚本需要有关异常终止的信息时,您才需要使用 exit。否则就没有必要。

我记得 Java 程序默认会以 0 退出 - 意味着正常终止。因此,在程序因某些错误而终止的情况下,您需要使用 System.exit(n) 。

示例(仅使用您最有可能想要实例化的静态方法...):

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
}

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
}
随风而去 2024-08-18 19:30:21

不要忘记,如果您执行 System.exit(),您以后将无法轻松地在独立库中使用您的方法。如果您想在现有解决方案之外重用代码(现在可能不会,但决定将来这样做),那么您将必须适当地重新访问和重构。

否则,最糟糕的情况是您在没有注意到 System.exit() 的情况下获取现有代码,使用它,然后让您的库在新应用程序中意外退出。

只是需要记住一些事情。代码重用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文