Member-only story

Why can’t I catch this Exception?

Catching exceptions in Flutter/Dart

Is there a difference when using await?

Jelena Lecic
2 min readApr 20, 2021

--

When using try/catch there is a difference when using await or not in front of your async function. If you do not wait your async function to be finished, catch section will not be called when an exception is fired inside you async method.

void main() {
try {
catchMeIfYouCan();
} catch (e) {
print(e.toString());
}
}
Future<void> catchMeIfYouCan() async {
await Future.delayed(Duration(seconds: 1), () {
throw Exception('did you?');
});
}

Console output for this example looks like this:

Uncaught Error: Exception: did you?

But, if you add await in front of the catchMeIfYouCan() method call:

void main() async {
try {
await catchMeIfYouCan();
} catch (e) {
print(e.toString());
}
}

Our exception will be caught :)

If you do not wanna wait for your async function to finish in order to be able to proceed with your program execution, but still be able to catch errors inside it, you can use .catchError() callback like this:

void main() {
catchMeIfYouCan().onError((e, _) {
print(e.toString());
});
}

Same thing will happen when using async generator:

yield* someMethod(someParameter);

Exceptions will not be caught by surrounding try/catch!
Make sure to catch exceptions inside the generator function itself(and maybe pass them to some generalized error handler or something like that).

There’s also one way you can catch your async function’s exceptions(pointed by out Gonçalo Palma), and that’s by using Zones:

import 'dart:async';void main() {
runZonedGuarded(() {
catchMeIfYouCan();
}, (e, s) {
print("Gotcha!!! :)");
});
}

This is the console output:

Gotcha!!! :)

It basically creates a new Zone in which onError callback(second parameter in runZonedGuarded() method) gets called when an exception occurs in a sync or an async function.

More about runZoneGuarded() can be found here.

Interested in joining Medium from my referral link? 💙
Thanks! :)

Thanks for your time and happy Fluttering! 💙

--

--

No responses yet

Write a response