Exit in Mercury
Here’s an idiomatic Java code example demonstrating the concept of program exit:
public class ExitExample {
public static void main(String[] args) {
// This println will be executed
System.out.println("Starting the program");
// This will not be executed due to System.exit()
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("This won't be printed!");
}));
// Exit with status 3
System.exit(3);
// This line will never be reached
System.out.println("This won't be printed either");
}
}
This Java program demonstrates the use of System.exit()
to immediately terminate the program with a specific exit status. Here’s a breakdown of the code:
We define a public class named
ExitExample
.In the
main
method, we first print a message to show that the program has started.We add a shutdown hook using
Runtime.getRuntime().addShutdownHook()
. This is similar to Go’sdefer
, but it won’t be executed when we useSystem.exit()
.We call
System.exit(3)
to immediately terminate the program with an exit status of 3.The last
println
statement will never be reached because the program exits before that.
To compile and run this program:
$ javac ExitExample.java
$ java ExitExample
Starting the program
To check the exit status in a Unix-like shell:
$ java ExitExample
Starting the program
$ echo $?
3
Note that the shutdown hook and the last print statement are never executed.
In Java, unlike Go, you can return an integer from the main
method to indicate the exit status. However, System.exit()
provides more control and can be called from anywhere in the program.
public static void main(String[] args) {
// ...
return 3; // This is equivalent to System.exit(3)
}
Using System.exit()
is generally preferred when you need to terminate the program from a non-main method or when you want to bypass finally blocks and shutdown hooks.
Remember that abruptly terminating a program with System.exit()
can leave resources in an inconsistent state, so it should be used judiciously.