Exceptions, Errors and asserts in Dart
Published in
3 min readFeb 19, 2021
What’s the difference?
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 anError
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…