18

When we learn C++ in school, our professor will tell us to write return 0; at the last line of codes in the main function and it is considered as a good programming practice.

In Java, I realise some people writes System.exit(0); at the last line of the main method.

However, in C++, if I use exit(0); I get penalized by my professor, because (in school) for procedural programming, we are expected to let the program flow till the end of main and let the program stop naturally.

My question: Is Java's System.exit(0); similar to C++'s return 0; ? (Or is it similar to C++'s exit(0))

Is it bad practice to use System.exit(0) in java when it is unnecessary (I.e.: writing it in last line of main method)?

7
  • 2
    That's rather contextual, as an "old school" developer, I was taught that there was entry point and one exit point (talking about functions and methods), but this can be held true for System.exit as well. The problem with using this within your code is the same as having multiple return statements in your functions/methods, they are easy to miss and can make understanding the code more difficult. Having said that, there are exceptions to every rule and some projects may require your terminate the running program midstream...but I would still be looking for away to avoid it... Commented Jun 25, 2014 at 6:28
  • 1
    I never used System.exit(0); at the last line of the main method.
    – earthmover
    Commented Jun 25, 2014 at 6:28
  • @AnkitLamba And much like C++, one is silently added. Commented Jun 25, 2014 at 6:29
  • Maybe this question will help explain: stackoverflow.com/q/3715967/3651800 Commented Jun 25, 2014 at 6:29
  • @MattCoubrough I just came from the link you pasted. Commented Jun 25, 2014 at 6:30

5 Answers 5

19

Java's System.exit(0) is like C++'s exit(0) in that

  • It terminates the process
  • It can be called from anywhere in the program.

The latter point makes it an “unstructured” control-flow construct that academic types tend to frown on. (In this case, they've got a good reason: If a function reports a failure via an exception (or old-fashioned return code), it's possible for the caller to recover from the error, but exit burns that bridge. Of course, sometimes errors do need to be treated as fatal.)

In C++, return 0 is equivalent to exit(0) if it's in the main function. (In other functions, it doesn't mean anything special.)

The relevant different between C++ and Java here is the return type of main.

  • In C++, main must return int. Normally, this would mean that it must have a return statement, but the C++ standard makes main a special case with an implied return 0; as the end if you don't write one.
  • In Java, main must return void.

In C++, it's common to write return statements in main, even though it's technically redundant, for stylistic consistency with all the other non-void functions in your program.

In Java, you can't return the exit code from main because it's a void function. So, if you want to explicitly specify an exit code, you have to use System.exit.

It's not wrong to end every Java main function with System.exit(0), but it's just not idiomatic to do so unless you've got a construct like

public static void main(String[] args) {
   try {
       //... do the work
       System.exit(0);
   } catch (Throwable t) {
       //... report the error
       System.exit(1);
   }
}
5
  • 11
    It is wrong to end the main method with an exit if your application uses non-daemon threads for longer than the main thread's lifetime.
    – Darkhogg
    Commented Jun 25, 2014 at 11:54
  • @Darkhogg So what's the right way to set exit code in java? Join on all non-daemon threads first and then exit(1)?
    – Cruncher
    Commented Jun 25, 2014 at 14:03
  • Won't exit(0) mess with RAII? Files/sockets/etc. opened in main may not flush their output correctly.
    – josefx
    Commented Jun 30, 2014 at 20:06
  • @josefx: Java doesn't have RAII. Files/sockets/etc. must be explicitly closed. (Though, recent versions of the language have a try-with-resources construct, similar to C# using, that make this a little more convenient.)
    – dan04
    Commented Dec 3, 2016 at 0:49
  • @dan04 I think I was referencing the c++ exit(0) in main part. An exit(0) in main can prevent the destructors of static objects from running, which may result in unflushed files, sockets, etc. .
    – josefx
    Commented Dec 3, 2016 at 9:52
9

In Java System.exit(0),System.exit(1),System.exit(-1) is used to know if the execution of the program went good or bad. 0 is used when execution went fine. 1, -1, whatever != 0 when some error occurred, you can use different values for different kind of errors.

You can also say it like this:

0 mean everything Okay

1 means something which I expecting to go wrong went wrong

-1 means something which I didn't expect went wrong

The Java Doc says:

The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.


Is Java's System.exit(0); similar to C++'s return 0; ?

Yes they both are similar.

Is it bad practice to use System.exit(0) in java when it is unnecessary

I would not say it is a bad practice but yes you should be aware of when to use it and where to use it. You can use it to throw an error for a command line tool via a exit code instead of throwing an exception. System.exit(0) terminates the JVM so you should be very much sure where to use that.

An example for that:

try {  
    runTheWholeApplication();  
    System.exit(0);  // Signifying the normal end of your program
} catch (Throwable t) {  
    reportErrorSomehow(t);  
    System.exit(1);  // Signifying that there is an error
}
3
  • So I assume it acts similar to C++'s exit(0). Then maybe we should avoid using it unless we are writing programs with threads..etc ? Commented Jun 25, 2014 at 6:33
  • 2
    @user3437460 Yes. It's the same thing. Commented Jun 25, 2014 at 6:36
  • 1
    On POSIX systems, the exit code is an 8-bit unsigned integer. You can return -1, but it gets interpreted as 255 (due to two's complement).
    – dan04
    Commented Jun 25, 2014 at 14:05
4

When we learn C++ in school, our professor will tell us to write return 0; at the last line of codes in the main function and it is considered as a good programming practice.

That's debatable. Has he also told you that return 0; is implicit inside main? Personally, I never write the redundant return 0; inside main, and I almost never see it in other people's code either.

1
3

Yes. Java's System.exit(0); is a direct analogue because the prototypical Java main method is defined as

public static void main(String[] args) {
}

So it literally cannot return an int (although it can simply return;). In C++ you could exit(0); which is also equivalent.

2
  • ...and what about return;
    – earthmover
    Commented Jun 25, 2014 at 6:29
  • 1
    @AnkitLamba Edited. Yes. You can simply return. Commented Jun 25, 2014 at 6:30
3

The original operating system Unix heavily relied on command line scripts using and combining many small programs. A return code of a program was used for the control flow. Return code 0 meaning everything okay, non-zero for errors.

So the C int main(...) is a direct mapping, and return 0; at the end appropiate. An exit there is like throwing an exception, bypassing any return. It also disables calling the main from another program.

In Java public void main(...) this was simplified, and 0 is implicit. System.exit(0); has the same bad assumption that no other program calls main. Though in general void mirrored the 99% usage, now System.exit(...); is inevitable for a non-zero error code.

This must also be seen as a more general design decision; C heavily relies on return codes of functions, which makes the control flow difficult or error prone, whereeas Java introduced the usage of Exceptions as possible obligatory control flow, with a freely chooseable catch. Nowadays an alternative to System.exit(13) might be throw new IllegalArgumentException("Unlucky");.

5
  • So in your opinion, is it bad practice to use System.exit(0) in last line of java main? Commented Jun 25, 2014 at 7:05
  • 1
    @user3437460:- No it is not a bad practice. I would explain a scenario like when you're writing a batch or shell script, every program the script runs has an error code on exit. Typically, if the error code is zero no action needs to be taken but if the error code is non-zero you may want to write a routine to deal with it, even if it only quits prematurely. So in this case it is not a bad idea to use System.exit() Commented Jun 25, 2014 at 7:09
  • Yes, superfluous and doing more work, like x = x; or return;. Mind, for a program that uses those return codes, it might be considered documentation: a hint.
    – Joop Eggen
    Commented Jun 25, 2014 at 7:09
  • @JoopEggen Thanks for reply, your solution is more in depth than the rest. + 1 from me Commented Jun 25, 2014 at 7:13
  • 2
    @user3437460 you are right too; but a JVM program exit normally does return 0, so one does not need to write it explicitly; just like writing return; at the end of a void function is a sign of an uncertain programmer. But as said above, it could be styling, to list all System.exit(...)s.
    – Joop Eggen
    Commented Jun 25, 2014 at 7:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.