Exit in Logo
Here’s an idiomatic Java example demonstrating the concept of program exit, similar to the Go example provided:
This Java program demonstrates how to exit a program with a specific status code. Let’s break it down:
We define a public class named
ProgramExit
. In Java, the class name should match the file name, so this code should be in a file namedProgramExit.java
.Inside the
main
method, we useRuntime.getRuntime().addShutdownHook()
to add a shutdown hook. This is similar to Go’sdefer
, but it’s important to note that shutdown hooks in Java are not guaranteed to run when usingSystem.exit()
.We use
System.exit(3)
to immediately terminate the program with a status code of 3. This is equivalent to Go’sos.Exit(3)
.
To run this program:
- Save the code in a file named
ProgramExit.java
. - Open a terminal and navigate to the directory containing the file.
- Compile and run the code:
To check the exit status in a Unix-like shell:
Note that the “!” from our shutdown hook is not printed, as System.exit()
terminates the JVM before the shutdown hooks can be executed.
In Java, unlike C or Go, the main
method doesn’t return an integer to indicate the exit status. Instead, we use System.exit(int status)
to exit with a non-zero status code.
It’s worth mentioning that while System.exit()
is available, it’s generally considered a harsh way to terminate a program. In most cases, it’s better to let the program exit naturally by reaching the end of the main
method, which implicitly exits with status 0.
This example demonstrates how to explicitly exit a Java program with a specific status code, which can be useful in scenarios where you need to indicate success or failure to external processes or scripts that may be running your Java application.