Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I exit only my sub-program, not the whole VM?

I have a Java swing launcher program to launch another class (running its main method). Each program has its cancel button to exit itself.

I use System.exit(0); when this cancel button is pressed.

The launcher program does this in actionPerformed:

if (source==carMenuItem) {
    ta.append("Car launched\n");
    TestCar.main(par);

}
if (source==DialogboxMenuItem) {
    ta.append("Dialogbox launched\n");            
    DialogBox.main(par);
}        
if (source==LengthConversionMenuItem) {
    ta.append("LengthConversion launched\n");            
    LengthConversion.main(par);           
}

When I press the program's cancel button, it also closes my launcher program. How can I avoid this situation?

like image 433
hkguile Avatar asked Sep 13 '11 06:09

hkguile


People also ask

How do I exit a Java program without System exit?

Exit a Java Method using Return 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. The return keyword can be used to exit any method when it doesn't return any value.

How do you terminate a program in Java from inside the program?

exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination.

What can I use instead of System exit in Java?

The main alternative is Runtime. getRuntime(). halt(0) , described as "Forcibly terminates the currently running Java virtual machine". This does not call shutdown hooks or exit finalizers, it just exits.


1 Answers

System.exit() terminates the VM therefore your initial thread is terminated also, simply return from your main() method.

After reviewing you code: Not all classes are supposed to have a main() method (If not also used standalone). You should consider to call a constructor to create an instance of a class and call a method not named main().

like image 81
stacker Avatar answered Oct 03 '22 08:10

stacker