9

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)

2
  • 2
    I'd personally exit gracefully rather than throwing an exception. Commented Feb 13, 2013 at 15:04
  • I guess it depends who the user of your program is and how you want to alert him/her. If your program is just a service then i would go with System.exit() option, as i wouldnt like to have uneccessary exceptions in my logs. If your program has a GUI either way you will need to alert the user appropriately, thus any kind of exception should be caught and a dialog box should explain the end user why the program has stopped. Commented Feb 13, 2013 at 15:06

6 Answers 6

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

If you want a stack trace, go with the RuntimeException, if not System.exit(1) is cleaner.

Comments

1

Either is good, but I would prefer to use the System.exit() as the RuntimeException could be considered misleading.

Comments

1

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.");
    }
}

3 Comments

What other information would be needed?I want to check if some conditions apply and if not end the main thread.
@Jim: Then you can do it the way posted in my answer.
Yes, if the condition is not met, the program will go to last line (print message) and terminate
0

Never force the exit. Program your runtime method in a way allowing your application to run out of methods and close by itself. I suggest drawing a graph before any structural application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.