# Exception Handling in asynchronous code

## Exception Handling with then (catchError)

{% embed url="<https://youtu.be/CfwBXW6B0SQ>" %}

```dart

void main() {
  
  //Exception Handling 

  print(" Start fetching images");

  getData().then((images) {
    return images + " " + "caption";
  }).then((captionedimages) {
    print(captionedimages + " " + " save to disk");
  }).catchError((err){
    
    // Logic  for handling error 
    
    print("Error : $err , Sorry for  the error , check if you are connected to internet");
    
  });

  print("Loading Images");
}

Future<String> getData() {
  Future<String> a = Future<String>.delayed(Duration(seconds: 5), () {
    // Logic
    print(" Image Fetched !!!!!");
    throw "404 Error";
  });

  return a;
}




```

If you want to read more about error handling , here is the official documentation&#x20;

{% embed url="<https://dart.dev/guides/libraries/futures-error-handling>" %}

## Exception Handling with async await( try catch block)

{% embed url="<https://youtu.be/mQ84q03BFP4>" %}

```dart
void main() async {
  
  // Hadling exception
  
  
  try{
  var images = await fetchImage();
  print(images);
  var capImages = await captionImages(images);
  print(capImages);
  var saved = await savetodisk(capImages);
  print(saved);  
    
  }
  
  catch(err){
    
    // logic for handling error 
    
    print("Error $err , check if you are connected to internet");
    
    
  }
  

}




Future<String> fetchImage() async {
  await Future<String>.delayed(const Duration(seconds: 5));
  throw "500 error";
}


Future<String> captionImages(images) async {
  await Future<String>.delayed(const Duration(seconds: 5));
  return images+" "+"caption";
}


Future<String> savetodisk(capImages) async {
  await Future<String>.delayed(const Duration(seconds: 5));
  return capImages+" "+"Saved";
}




```

{% hint style="info" %}
For advanced error Handling , you  should write a separate class which handles the error
{% endhint %}

You should go through the following codelab to get a better understanding of asynchronous programming in dart :-&#x20;

{% embed url="<https://dart.dev/codelabs/async-await#example-completing-with-an-error>" %}
