Exit in Fortress
Here’s an idiomatic Fortress code example that demonstrates the concept of exiting a program with a specific status code:
In Fortress, we can demonstrate the concept of exiting a program with a specific status code using the exit
function. Here’s an explanation of the code:
We define a
main
component that exports theExecutable
trait, which is required for the program to be runnable.Inside the
run
function (which is the entry point of a Fortress program), we first print a message indicating the program is starting.We use the
finally
function to register a cleanup action. In Fortress,finally
is similar todefer
in some other languages. It schedules a function to be called when the current function exits normally.We then call
exit(3)
, which immediately terminates the program with the status code 3.The cleanup action registered with
finally
will not be executed becauseexit
terminates the program immediately.
To run this Fortress program:
- Save the code in a file named
ExitExample.fss
. - Use the Fortress compiler to compile the program:
- Run the compiled program:
- Check the exit status:
Note that the “Program ending…” message is never printed because the exit
function terminates the program before the finally
block can be executed.
In Fortress, like in many other languages, using exit
to terminate a program should be done judiciously. It’s often better to allow the program to terminate naturally by reaching the end of the run
function, which gives finally
blocks and other cleanup mechanisms a chance to execute.
This example demonstrates how to use exit
in Fortress to terminate a program with a specific status code, and shows that cleanup actions registered with finally
are not executed when exit
is called.