7

Say I have the following code:

try {
    //Do something with File
} catch (FileNotFoundException e) {
    outputInfo("Error in IO Redirection", true);
    e.printStackTrace();
    System.exit(1);
}

My program exits right after this catch location, is a single thread (one main method) program and should not expect to recover from such an exception.

Should I really be using System.exit(1); ?

insidesin
  • 735
  • 2
  • 8
  • 26
  • Using an integer 1-127 in system.exit indicates abnormal termination of a program. If you don't want to perform any other operation after catch block you can use it or catch the exception and print with proper error message. – Shriram Aug 13 '15 at 15:36
  • What alternative are you considering in place of `System.exit(1);`? – jaco0646 Aug 13 '15 at 15:58
  • No alternative, I'm just wondering what is required to think about when I'm using `System.exit(1);` and what I should understand might go wrong in using this in all my Exception handling catches. – insidesin Aug 13 '15 at 16:00

2 Answers2

5

If you expect someone else to run your program, and they rely on the process status code to know if your program has succeeded or failed, then you should use System.exit(1);

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#exit%28int%29

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

dotvav
  • 2,808
  • 15
  • 31
  • What if your program makes use of a finally clause as well. `System.exit(1)` will definitely interfere, does that mean you may have to duplicate finishing up code prior to calling the exit? – insidesin Aug 13 '15 at 15:47
  • You may either put the `exit` statement out of the `catch` block, or create a [shutdown hook](http://stackoverflow.com/questions/2921945/useful-example-of-a-shutdown-hook-in-java) that will be executed on the JVM termination (after you call `exit`). – dotvav Aug 13 '15 at 15:50
2

One of the reasons to use a non zero exit code on failure of an application is that they can be used in batch files. If your application is a console application always use proper exit code. You don't know how it will be used in future.

Dakshinamurthy Karra
  • 5,353
  • 1
  • 17
  • 28
  • I agree. I love future-proofing, exit codes are rarely seen in programs I come across, bizarrely... maybe too much overhead thinking for most. – insidesin Aug 13 '15 at 15:47