Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exiting functions in main

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?

like image 603
AirUp Avatar asked May 01 '12 13:05

AirUp


People also ask

What is exit () function in C?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. The general form of the exit() function is as follows − void exit (int code);

What is exit function?

In the C Programming Language, the exit function calls all functions registered with atexit and terminates the program. File buffers are flushed, streams are closed, and temporary files are deleted.

How do you exit a main function in Python?

You can use sys. exit() to exit from the middle of the main function.

Does the exit (); function return a value?

Working of the exit() function in C++ Remember, the function exit() never returns any value.


2 Answers

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 ?
like image 173
jmj Avatar answered Nov 05 '22 09:11

jmj


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).

like image 27
Konstantin Tarashchanskiy Avatar answered Nov 05 '22 09:11

Konstantin Tarashchanskiy