我怎样才能知道我的程序是否正常终止?
如果我用 Java 编写了一个程序,我如何知道我的程序是正常终止还是正常退出?
If I have written a program in Java, how can I know if my program has terminated normally or exited normally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在这里猜测一点,因为你的问题有点模糊。但我假设您谈论的是在您的程序中找出该程序上次运行时是否正常终止。
如果您有配置目录或文件的内容,请在程序启动时在那里留下注释,并在进程正常退出时删除该注释。如果当您的程序启动时该注释仍然存在,则另一个实例仍在运行(您需要单独检查)或者它没有正常终止。
I'm guessing a little here, since your question is kinda vague. But I assume you talk about finding out within your program that this program terminated normally or not when it was last run.
If you got something of a configuration directory or file—leave a note there, when the program starts and remove said note when your process exits normally. If that note is still there when your program starts then either another instance is still running (something you'd need to check separately then) or it didn't terminate normally.
程序终止时,JVM 返回一个整数退出代码,0 表示程序正确终止,非零值通常表示错误情况。
如果你的程序正常结束(即main方法返回而没有抛出异常),那么JVM将返回0,否则,如果抛出异常并且没有捕获,那么JVM将返回一个非零错误代码。
您还可以通过
System.exit(int)
方法。这会导致 JVM 立即终止并返回指定的错误代码。假设您使用的是基于 Windows 的计算机,则可以通过回显
%ERRORLEVEL%
属性来查看返回的错误代码。例如,假设您有一个 Main 类,您可以看到如下错误代码:
如果您随后将 main 更改为调用
System.exit(1)
,则错误级别将如下所示:The JVM returns an integer exit code upon termination of your program, with 0 meaning the program terminated correctly, and a non-zero value usually representing an error condition.
If your program comes to an end normally (i.e. the main method returns without throwing an exception), then the JVM will return 0, otherwise, if an exception is thrown and not caught, then the JVM will return a non-zero error code.
You can also set the error code yourself, via the
System.exit(int)
method. This causes the JVM to immediately terminate and return the specified error code.Assuming you're on a Windows based machine, you can then see the error code returned by echoing the
%ERRORLEVEL%
property.For example assuming you have a class Main, you can see the error code like this:
If you then changed main to call
System.exit(1)
, then the error level would look like this: