How to handle exception in asynchronous function in C# 5.0
Exception handling in asynchronous function
In this tutorial we will try to understand how to implement
try-catch block in asynchronous function in C# 5.0. I hope you have idea about asynchronous function and probably you have implemented it practically. Now we
will see how to implement try-catch block in asynchronous function.
Implement traditional try-catch block
Try-catch block in asynchronous function is not like normal
try-catch block in C# function. The implementation is little bit different. At
first we will implement try-catch block like simple function.
Have a look on below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Asynchronious
{
class TestAsync
{
public Task LongProcess()
{
return Task.Run(() => {
System.Threading.Thread.Sleep(1000);
throw new Exception("Our own Exception");
});
}
public async void CallLongTask()
{
await LongProcess();
}
}
class Program
{
public static void Main(String[] args)
{
try
{
TestAsync obj = new TestAsync();
obj.CallLongTask();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
Here is output screen.

So, though we have wrapped all function within try-catch
block but catch block is fail to catch the exception. Then, what is the solution? We have to implement try-catch block within LongProcess()
function.
Let’s see below code.
Implement try-catch within function
Here we have implemented try-catch block within LongProcess().
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace Asynchronious
{
class TestAsync
{
public Task LongProcess()
{
return Task.Run(() => {
try
{
System.Threading.Thread.Sleep(1000);
throw new Exception("Our own Exception");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
});
}
public async void CallLongTask()
{
await LongProcess();
}
}
class Program
{
public static void Main(String[] args)
{
TestAsync obj = new TestAsync();
obj.CallLongTask();
Console.ReadLine();
}
}
}
Here is sample output.

Now, we are seeing that catch block is able to catch the
exception.
Conclusion :-
In this article we have learned how to implement try-catch in asynchronous function in C# 5.0. Hope you have understood the concept.