Exit in Crystal
Here’s an idiomatic Crystal example that demonstrates the concept of exiting a program:
This Crystal program demonstrates how to use the exit
method to immediately terminate a program with a specified status code. Here’s a breakdown of the code:
We use the
at_exit
hook to register a block of code that should run when the program exits normally. However, this block will not be executed when usingexit
.We print a message to inform the user that the program is about to exit.
The
exit(3)
call immediately terminates the program with a status code of 3. Any code after this line will not be executed.
To run this program:
- Save the code in a file named
exit_example.cr
. - Open a terminal and navigate to the directory containing the file.
- Compile and run the code using the Crystal compiler:
To build a binary and check the exit status:
Note that the message “This will not be printed!” from the at_exit
hook is never displayed, as exit
bypasses normal program termination.
In Crystal, unlike some other languages, the main
function’s return value is not used to determine the exit status. Instead, you should use the exit
method to set a non-zero exit status explicitly.
This example showcases Crystal’s simplicity in handling program termination and demonstrates how to use the exit
method effectively in your Crystal programs.