I am writing an application program using swing. I need to exit from the application by clicking the JButton
for that can i use System.exit()
or should i use some other methods, which is the best practice. If calling System.exit()
is not best practice then tell the reason and tell the alternative way to exit from the application.
exit() method terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
System. exit function has status code, which tells about the termination, such as: exit(0) : Indicates successful termination. exit(1) or exit(-1) or any non-zero value – indicates unsuccessful termination.
return statement is used inside a method to come out of it. System. exit(0) is used in any method to come out of program.
You can end a Java program by using the “exit()” method of the Java “System” class. It terminates the currently running JVM. Here, the System. exit() method has a parameter 0, which indicates that the program will terminate without any error.
In general, calling System.exit(...)
anywhere but the "main" method of an application can be problematic for (at least) the following reasons.
It is an impediment to reusing your code.
It makes unit testing hard. For example, if your code calls System.exit
when your JUnit tests exercise some error handling, that it the end of your test sequence!
The specific case of calling System.exit(...)
in the button listener for the "exit" button is not so bad. You are unlikely to want reuse the button listener somewhere that doesn't also require this behaviour. Also, you can probably figure out a work-around for the unit testing conundrum; e.g. don't unit test that particular method!
However, I think I'd still try to get the exit happen a different way. For example, have the main
method launch everything and then block on a CountDownLatch, then have the button listener decrement the latch. When the main
method unblocks, it executes the relevant shutdown code and returns or exits as appropriate.
Personnaly, I do consider as best practice to let application exit by itself : if you write a main class with a main(String[] args)
, with empty code, running it will exit silently from Java program.
But, in most times, like most of developpers, I rely upon System.exit(/an exit code/)
, especially for Swing applications, where the Swing EDT will run endlessly, as justkt wrote.. The known drawxback of this method is that most of applciation code is not called, what I avoid by setting a shutdown hook by calling Runtime.addShutdownHook(Thread)
, which will allow me to clean application (close threads, and so on).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With