Exception Handling in C# Asynchronous Programming

Welcome to the Asynchronous Programming series. In the previous three articles we explained the async and await keywords and the return type of asynchronous methods and tasks. You can read them here.

  1. Asynchronous programming in C# 5.0: Part-1: Understand async and await
  2. Asynchronous Programming in C# 5.0 Part 2: Return Type of Asynchronous Method
  3. Asynchronous Programming in C# 5.0 Part 3: Understand Task in Asynchronous programming.

In this article we will explain Exception Handling in asynchronous programming. I hope you are experienced with Exception Handling in C# but may not know how to implement Exception Handling in asynchronous programming. Let's see how to implement try-catch blocks in asynchronous programming. Have a look at the following code.

Traditional Try-Catch in Asynchronous programming

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7. namespace Asynchronious  
  8. {  
  9.     class Test  
  10.     {  
  11.         public Task ShowAsync()  
  12.         {  
  13.             return Task.Run(()=>{  
  14.                 Task.Delay(2000);  
  15.                 throw new Exception("My Own Exception");  
  16.             });  
  17.         }  
  18.         public async void Call()  
  19.         {  
  20.             await ShowAsync();  
  21.         }  
  22.     }   
  23.     class Program  
  24.     {  
  25.         public static void Main(String [] args)  
  26.         {  
  27.             Test t = new Test();  
  28.             try  
  29.             {  
  30.                 t.Call();  
  31.             }  
  32.             catch (Exception ex)  
  33.             {  
  34.                 Console.WriteLine(ex.Message);  
  35.             }  
  36.             Console.ReadLine();  
  37.         }  
  38.     }  
  39. }  
We have declared a Test class with an asynchronous function, ShowAsync(), that will throw an exception. One more function (Call) will call the ShowAsync() function. From the Main() function we are calling the Call() function wrapping try catch blocks. And we hope that in the catch block the exception will be handled. Have a look at the following output.

image1.gif

Oh! Catch is not handling an exception? Why? The reason is it's asynchronous in nature. As we know, in asynchronous programming, control does not wait for the function's result and it executes the next line. So when the function throws an exception, at that moment the program control is out of the try-catch block. This is the reason for it.

Implement try-catch within function


Let's implement a try-catch block within an asynchronous function. This is the solution to catch exceptions in asynchronous methods. Have a look at the following code. If you look closely inside the ShowAsync() function then you will find we have implemented a try-catch within Task.run(). Within Task.run() all processes are executed synchronously (in our example) . So, if there is any exception then it will be caught by the Exception Handling block.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7. namespace Asynchronious  
  8. {  
  9.     class Test  
  10.     {  
  11.         public Task ShowAsync()  
  12.         {  
  13.                 return Task.Run(() =>  
  14.                 {  
  15.                     try  
  16.                     {  
  17.                         Task.Delay(2000);  
  18.                         throw new Exception("My Own Exception");  
  19.                     }  
  20.                     catch (Exception ex)  
  21.                     {  
  22.                         Console.WriteLine(ex.Message);  
  23.                         return null;  
  24.                     }  
  25.                 });  
  26.         }  
  27.         public async void Call()  
  28.         {  
  29.             try  
  30.             {  
  31.                 await ShowAsync();  
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                 Console.WriteLine(ex.Message);  
  36.             }  
  37.         }  
  38.     }   
  39.     class Program  
  40.     {  
  41.         public static void Main(String [] args)  
  42.         {  
  43.             Test t = new Test();  
  44.             t.Call();  
  45.             Console.ReadLine();  
  46.         }  
  47.     }  
  48. }  
Now, you may ask a question. We have implemented a try catch block within Task and it's fine. But what need is there for implementing a try-catch within the Call() function? The reason is that when an asynchronous function fails to execute a Task, it throws a Task Cancelled exception. And we need to implement a mechanism to catch this exception.

Here is the output screen.

image3.gif

We are seeing that now the Exception Handling block is capable of the catching the exception.

Now the question is, is it possible to wrap a try-catch block over an asynchronous function as is done for traditional synchronous functions? The answer is, we can but with a limitation. What is the limitation? The exception should occur outside of Task process statement. Then Exception Handling block can catch the exception. Let's see the following example.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading;  
  6. using System.Threading.Tasks;  
  7. namespace Asynchronious  
  8. {  
  9.     class Test  
  10.     {  
  11.         public Task ShowAsync()  
  12.         {  
  13.             throw new Exception("My Own Exception");  
  14.             return Task.Run(() =>  
  15.                 {  
  16.                     Task.Delay(2000);  
  17.                 });              
  18.         }  
  19.         public async void Call()  
  20.         {  
  21.             try  
  22.             {  
  23.                await ShowAsync();  
  24.             }  
  25.             catch (Exception ex)  
  26.             {  
  27.                 Console.WriteLine(ex.Message);  
  28.             }  
  29.         }  
  30.     }   
  31.     class Program  
  32.     {  
  33.         public static void Main(String [] args)  
  34.         {  
  35.             Test t = new Test();  
  36.             t.Call();  
  37.             Console.ReadLine();  
  38.         }  
  39.     }  
  40. }  
Here the exception occurs outside of the Task, now the exception is caught by the try catch block from the calling location. Here is the sample output.

image4.gif

Conclusion

This article has explained Exception Handling in asynchronous programming. Hope you have understood it. In the next article I would like to discuss a few more real-world examples of asynchronous programming.
 
Author
Sourav Kayal
0 27.7k 24.4m
Next » Asynchronous Programming in C# 5.0 - Access Data Sing Asynchronous Function