Exit in Fortress
Here’s an idiomatic Fortress code example that demonstrates the concept of exiting a program with a specific status code:
component main
export Executable
run() =
println("Program starting...")
# This will not be executed due to the exit call
finally(fn() -> println("Program ending..."))
# Exit the program with status code 3
exit(3)
end
endIn 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
maincomponent that exports theExecutabletrait, which is required for the program to be runnable.Inside the
runfunction (which is the entry point of a Fortress program), we first print a message indicating the program is starting.We use the
finallyfunction to register a cleanup action. In Fortress,finallyis similar todeferin 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
finallywill not be executed becauseexitterminates 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:
$ fortc ExitExample.fss- Run the compiled program:
$ fort ExitExample
Program starting...- Check the exit status:
$ echo $?
3Note 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.