I'm writing a Java program that reads in a file of words. The program crucially depends on this file, so I really do want the program to end if for whatever reason there's an IOException when reading the file.
What's the best way to end the program? I think I'm forced to surround my file-reading inside a try/catch block, so should I add a System.exit(0)
inside my catch? For example, should I do something like the following?
try { BufferedReader br = new BufferedReader(new FileReader("myfile.txt")); String line; while ((line = br.readLine()) != null) { // process... } } catch(IOException e) { System.out.println("Error: " + e); System.exit(0); // ??? }
If you let the exception propagate all the way up to the main() method, the program will end. There's no need to call System. exit , just allow the exception to bubble up the stack naturally (by adding throws IOException ) to the necessary methods.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Using the Throws keyword Throws is a keyword used to indicate that this method could throw this type of exception. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions.
If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.
If you let the exception propagate all the way up to the main()
method, the program will end. There's no need to call System.exit
, just allow the exception to bubble up the stack naturally (by adding throws IOException
) to the necessary methods.
Edit: As @Brian pointed out, you may want to catch the IOException
in your main
method, and call System.exit
there instead, supplying a human-readable error message (stack traces can scare people). Also, as @MeBigFatGuy said, calling System.exit
from inside your code stack is bad practice, and limits the reuseability of the code. If you must use System.exit
, then keep it inside the body of the main
method.
That's fine. However 0
as an exit code means the program ended as expected. You'll want to use a different number ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With