If I want to check if some preconditions are present in order to run a java program what is best?
Do:
System.exit(1);
Or throw a RuntimeException
in main
to end the main thread? (No other threads running yet)
Exit a Java Method using Returnexit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function.
How do you end a Java program if a condition is met? To end or terminate a program in Java, use the System. exit() method or a return statement.
Java break Statement break is used to break or terminate a loop whenever we want. Just type break; after the statement after which you want to break the loop.
exit() Method which terminates the current Java Virtual Machine running on the system.
You're better off calling exit
as exceptions are used to help you catch errors in programming flow and deal with them accordingly.
From a user's perspective having the application print to System.err
the issues and then closing gracefully is much more intuitive than seeing a stack trace or other code notations like EXCEPTION
that they shouldn't be expected to understand.
Ideally you terminate your threads gracefully. System.exit(1)
works too, but it is better if your threads get signalled that they need to stop what they're doing and terminate by finishing what they're doing (i.e. executing their method till the end). It depends on your design obviously.
Throwing a RuntimeException
seems too ungraceful and could lead you to behaviour you don't actually want.
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