In an application we sometimes want terminate the execution of our application, for instance because it cannot find the required resource.
To terminate it we can use exit(status)
method in java.lang.System
class or in the java.lang.Runtime
class. When terminating an application we need to provide a status code, a non-zero status assigned for any abnormal termination.
package org.kodejava.example.lang;
import java.io.File;
public class AppTerminate {
public static void main(String[] args) {
File file = new File("config.xml");
int errCode = 0;
if (!file.exists()) {
errCode = 1;
}
// When the error code is not zero go terminate
if (errCode > 0) {
System.exit(errCode);
}
}
}
The call to System.exit(status)
is equals to Runtime.getRuntime().exit(status)
. Actually the System
class will delegate the termination process to the Runtime
class.
Running the code give the following output because it could not found the config.xml
file.
Process finished with exit code 1
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019