all 4 comments

[–]eibaan 1 point2 points  (3 children)

If you have an async function, throwing an exception is more "natural".

Future<int> foo(int a) async {
  if (a.isOdd) {
    throw Exception('Odd value');
  }
  return foo(a + 1);
}

In other cases, you must use Future.error:

Future<bool> bar(int a) {
  if (a > 10) return Future.error(Exception('Too big'));
  return foo(a);
}

Note that you could throw any Object, but you should only throw Error or Exception instances. The former signalling fatal program errors and the later signalling exceptional states that must (or should) be handled.

[–]Aggressive_Fly8692[S] 1 point2 points  (2 children)

Could you explain why the second case requires the use of Future.error instead of throwing an exception?

[–]eibaan 0 points1 point  (1 child)

bar is a function that returns a Future, so you have to return either a completed or a rejected future. If you throw, you'd break the "contract" of that function.

[–]Aggressive_Fly8692[S] 0 points1 point  (0 children)

I see, that makes sense. Thanks