Panic in Dart

In Dart, we use exceptions to handle unexpected errors. The concept of panic in Go is similar to throwing an exception in Dart.

import 'dart:io';

void main() {
  // We'll use exceptions throughout this site to check for
  // unexpected errors. This is the only program on the
  // site designed to throw an exception.
  throw Exception('a problem');

  // A common use of exceptions is to abort if a function
  // returns an error that we don't know how to (or want to) handle.
  // Here's an example of throwing an exception if we get an
  // unexpected error when creating a new file.
  try {
    File('/tmp/file').createSync();
  } catch (e) {
    throw Exception('Failed to create file: $e');
  }
}

Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.

When the first exception in main is thrown, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first exception.

$ dart run panic.dart
Unhandled exception:
Exception: a problem
#0      main (file:///path/to/panic.dart:7:3)
#1      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:295:32)
#2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)

Note that unlike some languages which use exceptions for handling of many errors, in Dart it is idiomatic to use nullable types and the Result pattern for error handling where possible, reserving exceptions for truly exceptional circumstances.