Should I use System.exit (1) when an Exception is thrown?

Let's 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 immediately after this catch location, it is a program with one thread (one main method) and should not expect recovery from such an exception.

Should I use System.exit(1); ?

+6
source share
2 answers

If you expect someone else to run your program and they will rely on the process status code to find out if your program was successful or unsuccessful, then you should use System.exit(1);

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

Closes a running Java virtual machine. The argument serves as a status code; by convention, a non-zero status code indicates abnormal termination.

+4
source

One reason for using a non-zero exit code when an application crashes is that they can be used in batch files. If your application is a console application, always use the correct exit code. You do not know how it will be used in the future.

+2
source

All Articles