Open
Description
Often if you're in a try block, you want to catch exceptions.
But if you omit the await
errors might flow through.
See https://dartpad.dev/c8deb87cee33b48316fc0f5cf4b1891f
Future<void> main() async {
for (var func in [goodCatch, badCatch]) {
print('Running $func');
try {
await func();
} catch (e) {
print('Why was this not caught? $e');
}
print('');
}
}
Future<void> goodCatch() async {
try {
// `await` here is CRITICAL!
return await badAsync();
} on StateError catch (e) {
print('Caught "$e"!');
}
}
Future<void> badCatch() async {
try {
// No await, so the state error is not caught!
return badAsync();
} on StateError catch (e) {
print('Caught "$e"!');
}
}
Future<void> badAsync() async {
throw StateError('bad!');
}
Running Closure 'goodCatch'
Caught "Bad state: bad!"!
Running Closure 'badCatch'
Why was this not caught? Bad state: bad!