I have something like this:
Future<void> f1() { ... }
Future<void> f2() { ... }
Future<void> f3() { ... }
void main() async
{
f1();
f2(); // might throw an Exception
await f3();
}
Note - I am deliberately not awaiting f1 or f2, I am only awaiting the consequences in f3.
How do I handle the possibility of an exception in f2 ? The normal try / catch procedure doesn't work.
I have seen some discussion of catchError but I don't really understand it.
I would like to do the equivalent of:
Future<void> f1() { ... }
Future<void> f2() { ... }
Future<void> f3() { ... }
void main() async
{
f1();
try
{
f2(); // might throw an Exception
}
on MyException catch( e )
{
print('this is what I expected to happen, so carry on regardless');
}
await f3();
}
As you noted, you can use
Future.catchError:Note that
Future.catchErrorcan be tricky to use. You always can wrap yourFuturein another function that internally usesawaitwithtry-catch, and then the caller doesn't need to useawait:If you don't need to do any handling for the error and want to ignore all failures, you also can use the
ignoreextension method onFutures: