Member-only story

Why can’t I catch this Exception?

Catching exceptions in Flutter/Dart

Is there a difference when using await?

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 :)

--

--

No responses yet