Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return & system.exit()

 
Ambika Jain
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is using "return" or "System.exit()" same if used in main() method ?

Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ambika Jain
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Hung Yee
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When in doubt, use return. It cleans up better before shutting down.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic