Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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...');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading