How can I discover if my program has terminated normally?
If I have 开发者_运维知识库written a program in Java, how can I know if my program has terminated normally or exited normally?
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.
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:
C:\>java Main
C:\>echo %ERRORLEVEL%
0
If you then changed main to call System.exit(1)
, then the error level would look like this:
C:\>echo %ERRORLEVEL%
1
精彩评论