Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use System.exit(1) when catching an application-stopping Exception?

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); ?

like image 864
insidesin Avatar asked Aug 13 '15 15:08

insidesin


2 Answers

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.

like image 161
dotvav Avatar answered Nov 21 '22 15:11

dotvav


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.

like image 30
Dakshinamurthy Karra Avatar answered Nov 21 '22 16:11

Dakshinamurthy Karra