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

Time:12-03

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.

CodePudding user response:

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...');
}
  • Related