Exit in Dart
Here’s an idiomatic Dart example demonstrating the concept of exiting a program:
This Dart program demonstrates how to use the exit
function to immediately terminate the program with a specific exit code. Here’s a breakdown of the code:
We import the
dart:io
library, which provides theexit
function.In the
main
function, we first print a message to show that the program has started.We use
Future.delayed
to schedule a print statement to run after a 1-second delay. This demonstrates that scheduled tasks won’t be executed if we exit the program before they run.We call
exit(3)
to immediately terminate the program with an exit code of 3.The last print statement will never be reached because the program exits before it.
To run this program:
- Save the code in a file named
exit_example.dart
. - Open a terminal and navigate to the directory containing the file.
- Run the program using the Dart VM:
To check the exit code in a Unix-like system:
This will display the exit code of the last executed command, which in this case is 3.
In Dart, unlike some other languages, we don’t return a value from the main
function to set the exit code. Instead, we use the exit
function from the dart:io
library to explicitly set the exit code.
It’s important to note that using exit
will immediately terminate the program, bypassing any scheduled asynchronous operations or cleanup code. In most cases, it’s better to allow your program to complete naturally, only using exit
for exceptional circumstances.
This example demonstrates how to use exit
in Dart, which is conceptually similar to os.Exit
in Go, but with syntax and usage patterns that are idiomatic to Dart.