Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a java program if it is determined it should not run?

Tags:

java

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)

like image 655
Jim Avatar asked Feb 13 '13 15:02

Jim


People also ask

How do you stop a Java program from running?

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 stop a Java program if a condition is met?

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.

How do you end an endless loop in Java?

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.

Which Java statement is used to stop the execution of a Java program?

exit() Method which terminates the current Java Virtual Machine running on the system.


2 Answers

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.

like image 185
Grambot Avatar answered Oct 15 '22 03:10

Grambot


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.

like image 20
jbx Avatar answered Oct 15 '22 05:10

jbx