Exception Handling in asynchronous code

Exception Handling with then (catchError)


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

Exception Handling with async await( try catch block)

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";
}



For advanced error Handling , you should write a separate class which handles the error

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

Last updated