Exit in Groovy
Here’s an idiomatic Groovy example demonstrating the concept of exiting a program:
This Groovy script demonstrates how to exit a program with a specific status code. Let’s break it down:
We use the
@CompileStatic
annotation to enable static compilation, which can improve performance.We define a
main
method, which is the entry point of our Groovy script.We create a closure
goodbye
that prints “Goodbye!” and add it as a shutdown hook. Shutdown hooks are normally executed when the JVM is shutting down, but they won’t be executed when usingSystem.exit()
.We print a message to indicate the start of the program.
We use
System.exit(3)
to immediately terminate the program with a status code of 3. This is equivalent to theos.Exit(3)
in the original Go example.The last
println
statement will never be executed because the program exits before reaching it.
To run this Groovy script:
- Save the code in a file named
Exit.groovy
. - Open a terminal and navigate to the directory containing the file.
- Run the script using the
groovy
command:
To compile the Groovy script into a Java class and run it:
To check the exit status in Unix-like systems:
Note that the “Goodbye!” message is never printed because System.exit()
bypasses the normal shutdown process, including shutdown hooks.
In Groovy, like in Java, the main
method doesn’t return an integer to indicate the exit status. Instead, you need to use System.exit()
to set a non-zero exit status explicitly. This is similar to the behavior in the original Go example.
This example demonstrates how to exit a Groovy program with a specific status code and shows that code after the exit call is not executed, mirroring the behavior of the original Go example.