Flutter Community

Articles and Stories from the Flutter Community

Exceptions, Errors and asserts in Dart

Suragch
Flutter Community
Published in
3 min readFeb 19, 2021

--

What’s the difference?

Photo by Sarah Kilian on Unsplash

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.');
}

--

--

Flutter Community
Flutter Community

Published in Flutter Community

Articles and Stories from the Flutter Community

Suragch
Suragch

Written by Suragch

Flutter and Dart developer. Twitter: @suragch1, Email: suragch@suragch.dev

Responses (1)