Sunday 27 November 2016

.Net High Performance Part 5 :Exception Handling in .Net Task Parallel Library


In general.Net programming, exception handling is very straight forward. But this is not the case when it comes to the TPL.

If an exception occurred in a Task, even though if you invoke that Task in a thread where you do the exception handling, the Tasks's exception would bubble up to the OS level. This is simple because the Task is a different thread from the calling thread.

Example :

 

  try
  {
    // Some code 
    Task task = new Task.Factory.StartNew (()=> 
    {
       int i=0;
       int j= 89/i;
    }

   );

    // Some code 


  }
  catch(Exception Ex)
  {
   Console.WriteLine("An Exception occurred ! ");
  } 


} 

This divide by zero error is bubbling up to the OS level.
In order to mitigate this , we need to understand what kind of exception that is been thrown from the Task. We need to capture the AggregateException which is thrown from the code.


  try
  {
    // Some code 
    Task task = new Task.Factory.StartNew (()=> 
    {
       int i=0;
       int j= 89/i;
    }

   );

    // Some code 


  }
  catch(AggregateException Ex)
  {
   Console.WriteLine("Exception : {0}", Ex.InnerException.Message);
  } 
catch(Exception Ex) { Console.WriteLine("An Exception occurred ! "); } }


If there are more than one exception being thrown or if there are multiple tasks inside the exception handling block,

catch(AggregateException Ex)
  {
   Ex = Ex.Flatten();
   foreach(Exception ex in Ex.InnerExceptions)
      Console.WriteLine("Exception : {0}", ex.Message);
  } 



No comments:

Post a Comment