What's the recommended way in Dart: asserts or throw Errors

Asserts are ways to perform code useful in development only, without hindering the performances of release mode – usually to prevent bad states caused by a missing feature in the type system.

For example, only asserts can be used to do defensive programming and offer a const constructor.

We can do:

class Foo {
  const Foo(): assert(false);
}

but can't do:

class Foo {
  const Foo() { throw 42; }
}

Similarly, some sanity checks are relatively expensive.

In the context of Flutter, for example, you may want to traverse the widget tree to check something on the ancestors of a widget. But that's costly, for something only useful to a developer.

Doing that check inside an assert allows both performance in release, and utility in development.

assert(someVeryExpensiveCheck());

Background

  • In Dart an Exception is for an expected bad state that may happen at runtime. Because these exceptions are expected, you should catch them and handle them appropriately.
  • An Error, on the other hand, is for developers who are using your code. You throw an Error to let them know that they are using your code wrong. As the developer using an API, you shouldn't catch errors. You should let them crash your app. Let the crash be a message to you that you need to go find out what you're doing wrong.
  • An assert is similar to an Error in that it is for reporting bad states that should never happen. The difference is that asserts are only checked in debug mode. They are completely ignored in production mode.

Read more on the difference between Exception and Error here.

Next, here are a few examples to see how each is used in the Flutter source code.

Example of throwing an Exception

This comes from platform_channel.dart in the Flutter repo:

@optionalTypeArgs
Future<T?> _invokeMethod<T>(String method, { required bool missingOk, dynamic arguments }) async {
  assert(method != null);
  final ByteData? result = await binaryMessenger.send(
    name,
    codec.encodeMethodCall(MethodCall(method, arguments)),
  );
  if (result == null) {
    if (missingOk) {
      return null;
    }
    throw MissingPluginException('No implementation found for method $method on channel $name');
  }
  return codec.decodeEnvelope(result) as T;
}

The MissingPluginException here is a planned bad state that might occur. If it happens, users of the platform channel API need to be ready to handle that.

Example of throwing an Error

This comes from artifacts.dart in the flutter_tools repo.

TargetPlatform _currentHostPlatform(Platform platform) {
  if (platform.isMacOS) {
    return TargetPlatform.darwin_x64;
  }
  if (platform.isLinux) {
    return TargetPlatform.linux_x64;
  }
  if (platform.isWindows) {
    return TargetPlatform.windows_x64;
  }
  throw UnimplementedError('Host OS not supported.');
}

First every possibility is exhausted and then the error is thrown. This should be theoretically impossible. But if it is thrown, then it is either a sign to the API user that you're using it wrong, or a sign to the API maintainer that they need to handle another case.

Example of using asserts

This comes from overlay.dart in the Flutter repo:

OverlayEntry({
  @required this.builder,
  bool opaque = false,
  bool maintainState = false,
}) : assert(builder != null),
      assert(opaque != null),
      assert(maintainState != null),
      _opaque = opaque,
      _maintainState = maintainState;

The pattern in the Flutter source code is to use asserts liberally in the initializer list in constructors. They are far more common that Errors.

Summary

As I read the Flutter source code, use asserts as preliminary checks in the constructor initializer list and throw errors as a last resort check in the body of methods. Of course this isn't a hard and fast rule as far as I can see, but it seems to fit the pattern I've seen so far.


As asserts are ignored in production mode, you should use them as way to do initial tests to your code logic in debug mode:

In production code, assertions are ignored, and the arguments to assert aren’t evaluated.

Tags:

Dart

Flutter