Exit in Mercury
Here’s an idiomatic Java code example demonstrating the concept of program exit:
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:
To check the exit status in a Unix-like shell:
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.
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.