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?
System.exit()
will terminate the jvm initilized for this program, where return;
just returns the control from current method back to caller
Also See
- when-should-we-call-system-exit-in-java ?
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).
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.