Handling Asynchronous Errors

  • Handling Asynchronous Errors

Handling Asynchronous Errors

Asynchronous errors are handle like any other errors in the Asynchronous programming. Here is the simple example of how error is handled using try-catch and finally like any other handling errors. Example

void main() async {
  try {
    String data = await fetchUserData();
    print('User data: $data');
  } catch (error) {
    print('Error: $error');
  } finally {
    print('Fetch complete');
  }
}

Future<String> fetchUserData() async {
  await Future.delayed(Duration(seconds: 4));
  return 'User: Andy';
}