main()方法的Java应用程序退出代码如何工作? [英] How exactly works the Java application exit code of the main() method?

查看:550
本文介绍了main()方法的Java应用程序退出代码如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一个简单的命令行Java应用程序有以下疑问.

I have the following doubts related a simple command line Java application.

因此我有一个命令行应用程序,它是由 Main 类中定义的 main() 方法启动的.通常,此 main() 方法是使用以下签名定义的:

So I have this command line application that is started by a main() method defined inside a Main class. As usual this main() method is defined with this signature:

public static void main(String[] args) {

它的返回类型是 void ,这应该意味着它不返回任何值.但是,当其执行正确终止时,我会在IntelliJ控制台中获得以下消息.

It's return type is void, and that should mean it doesn't return any value. But when its execution correctly terminates I obtain following message in the IntelliJ console.

Disconnected from the target VM, address: '127.0.0.1:54090', transport: 'socket'

Process finished with exit code 0

exit code 0 到底代表什么?我认为这意味着该程序已正确完成其执行,而不会引起任何错误.

What exactly does represent the exit code 0? I think it means that the program have correctly completed its execution without incur into any error.

所以现在我有以下两个疑问:

So now I have the following 2 doubts:

  1. 如果是事实,为什么我的 main() 方法返回 void 会发生这种情况?

  1. If it is true why it happens if my main() method return void?

如果我的应用程序以错误结尾,如何返回另一个退出代码?

How can I return a different exit code if my application ended with an error?

是否有用于结束错误的标准退出代码值?

Is there a standard exit code value for ending with errors?

推荐答案

VM何时退出

  • 所有非守护进程线程都停止运行,或者
  • System.exit(exitCode)被称为
  • all of the non-daemon threads stop running, or
  • System.exit(exitCode) is called

在第一种情况下,退出代码为0.在第二种情况下,这是传递给exit()方法的退出代码.

In the first case, the exit code is 0. In the second case, it's the exit code passed to the exit() method.

不要忘记,即使您的main()方法返回了,程序也将继续运行,直到不再运行非守护程序线程为止.而且,VM中运行的任何线程都可以选择显式退出.

Don't forget that even if your main() method returns, the program will continue running until no non-daemon thread runs anymore. And any thread running in the VM can choose to exit explicitely.

退出代码0表示一切都按预期进行.您可以选择使用其他任何退出代码向环境发出异常信号.

The exit code 0 means that everything went as expected. you can choose to use any other exit code to signal an exceptional condition to the environment.

这篇关于main()方法的Java应用程序退出代码如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆