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)
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)
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.
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.
Not having more information than what you posted I would do something like this:
public static void main(String[] args) {
boolean precondition = ... // determine your precondition here
if (precondition) {
// run program
} else {
System.out.println("Preconditions not satisfied.");
}
}