Recover in Dart

Dart makes it possible to handle exceptions using try, catch, and finally blocks. This mechanism is similar to exception handling in many other languages and can be used to gracefully handle errors and prevent program crashes.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.

import 'dart:async';

// This function throws an exception.
void mayThrow() {
  throw 'a problem';
}

void main() {
  // We use a try-catch block to handle exceptions.
  try {
    mayThrow();
  } catch (e) {
    // The catch block is executed when an exception is thrown.
    // 'e' is the exception object.
    print('Caught exception: $e');
  } finally {
    // The finally block is always executed, whether an exception was thrown or not.
    print('Cleanup code in finally block');
  }

  // This code will run, because the exception was caught.
  print('After mayThrow()');
}

To run the program:

$ dart run recover.dart
Caught exception: a problem
Cleanup code in finally block
After mayThrow()

In this Dart example, we use a try-catch-finally block to handle exceptions. The mayThrow() function throws an exception, which is then caught in the catch block. The finally block is always executed, whether an exception was thrown or not, making it useful for cleanup operations.

Unlike Go’s panic and recover, Dart uses a more traditional exception handling mechanism. However, the concept of gracefully handling errors to prevent program crashes remains the same.