Daniel Dai
Daniel Dai

Reputation: 1059

Why exception is not caught this way in async function in Dart?

Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
  try {
  return Future.delayed(const Duration(seconds: 2),
      () => throw Exception('Logout failed: user ID is invalid'));
    
  } catch(e) {
    // Why exception is not caught here?
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}

It outputs

Fetching user order...
Uncaught Error: Exception: Logout failed: user ID is invalid

Which says the exception is not caught. But as you see, the throw Exception clause is surrounded by try catch.

Upvotes: 0

Views: 214

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76193

The try-catch block will only catch exception of awaited Future. So you have to use await in your code:

Future<void> fetchUserOrder() async {
// Imagine that this function is fetching user info but encounters a bug
  try {
  return await Future.delayed(const Duration(seconds: 2),
      () => throw Exception('Logout failed: user ID is invalid'));
    
  } catch(e) {
    // Why exception is not caught here?
    print(e);
  }
}

void main() {
  fetchUserOrder();
  print('Fetching user order...');
}

Upvotes: 3

Related Questions