6

I am relatively new to Stackoverflow and Java, but I have a little experience in C. I liked the very clean way of C exiting the programs after a malfunction with the 'exit()' function.

I found a similar function System.exit() in Java, what differs from the C function and when should I use a 'System.exit()' best instead of a simple 'return' in Java like in a void main function?

jmj
  • 237,923
  • 42
  • 401
  • 438
AirUp
  • 426
  • 1
  • 8
  • 18

3 Answers3

6

System.exit() will terminate the jvm initilized for this program, where return; just returns the control from current method back to caller


Also See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Is that bad? If the main function fails, a termination of the JVM is okay if it is a simple program? – AirUp May 01 '12 at 13:59
  • 1
    Yes should be ok with normal progra, but mostly it is used where we want to terminate the application after realizing all the aquired resources – jmj May 01 '12 at 14:01
3

System.exit() will exit the program no matter who calls it or why. return in the main will exit the main() but not kill anything that called it. For simple programs, there is no difference. If you want to call your main from another function (that may be doing performance measurements or error handling) it matters a lot. Your third option is to throw an uncaught runtime exception. This will allow you to exit the program from deep within the call stack, allow any external code that is calling your main a programmatic way to intercept and handle the exit, and when exiting, give the user context of what went wrong and where (as opposed to an exit status like 2).

2

System.exit() may be handy when you're ready to terminate the program on condition of the user (i.e. a GUI application). return is used to return to the last point in the program's execution. The two are very different operations.

Makoto
  • 104,088
  • 27
  • 192
  • 230