| Author |
return & system.exit()
|
Ambika Jain
Ranch Hand
Joined: Jan 27, 2005
Posts: 48
|
|
Is using "return" or "System.exit()" same if used in main() method ? Thanks.
|
Ambika Jain
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
Returning from main() will only stop the program if no other non-daemon threads are running. So, for example, if the program has a GUI, then the event thread is running, so returning from main will not stop your program. System.exit() will, however, stop your program no matter how many threads are running.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Ambika Jain
Ranch Hand
Joined: Jan 27, 2005
Posts: 48
|
|
Thanks for the reply. If I am validating the arguments passed to the program, should I use system.exit() or return, if the arguments are invalid. Thanks.
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
|
System.exit() is a more abrupt way to stop your program. For example, if you call System.exit() from a try or catch block, any finally clause is ignored. System.exit() may be the most practical was to stop applications like Java Swing that have never-ending non-daemon threads.
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
Hung Yee
Greenhorn
Joined: Dec 22, 2004
Posts: 18
|
|
|
If it was me, I'd display some friendly message to the user saying what argument(s) was bad and why, then return from the main method.
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
|
When in doubt, use return. It cleans up better before shutting down.
|
 |
David Harkness
Ranch Hand
Joined: Aug 07, 2003
Posts: 1646
|
|
|
The nice thing about System.exit() is that you can pass an error code that, if the JVM is set up correctly for the O/S, it should pass to whomever called your program. This is why in C main() returns int.
|
 |
 |
|
|
subject: return & system.exit()
|
|
|