Exit in Dart

Here’s an idiomatic Dart example demonstrating the concept of exiting a program:

import 'dart:io';

void main() {
  // This print statement will be executed
  print('Starting the program');

  // This will not be executed due to the exit call
  Future.delayed(Duration(seconds: 1), () {
    print('This will not be printed');
  });

  // Exit the program with status code 3
  exit(3);

  // This line will never be reached
  print('This will not be printed either');
}

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:

  1. We import the dart:io library, which provides the exit function.

  2. In the main function, we first print a message to show that the program has started.

  3. 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.

  4. We call exit(3) to immediately terminate the program with an exit code of 3.

  5. The last print statement will never be reached because the program exits before it.

To run this program:

  1. Save the code in a file named exit_example.dart.
  2. Open a terminal and navigate to the directory containing the file.
  3. Run the program using the Dart VM:
$ dart run exit_example.dart
Starting the program

To check the exit code in a Unix-like system:

$ echo $?
3

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.