Threading Simplified: Part 6 (Exception Handling)

I am again here to continue the discussion around Threading. Today we will discuss about Exception Handling and related concepts.

In case, you didn’t have a look at our previous posts, you can go through the following,

Let’s start with a simple example to understand the concepts.

  1. staticvoidDoWork()   
  2. {  
  3.     thrownewArgumentNullException();  
  4. }  
  5.   
  6. staticvoid Main(string[] args)   
  7. {  
  8.     Console.Title = "Threading Exception Handling Demo";  
  9.     try {  
  10.         newThread(DoWork).Start();  
  11.     } catch (Exception ex)  
  12.     {  
  13.         Console.WriteLine("Exception {0}", ex.Message);  
  14.     }  
  15. }  
Run the program in debug mode and you will see the following result,

code

You can see in the above example that the exception is not getting caught in the parent try…catch block from where DoWork is called, but why?

In case, you didn’t figured out why it’s happening like this then think about fundamental concept of thread that it follows its own execution path.

Well, then how to make it work. It’s simple, just put try..catch inside the DoWork method as in the following,

code

So now we figured out that we need to put try..catch block in each worker threads method in order to catch their exceptions.

All right, but don’t we have any other way to catch the exceptions in the calling thread method body?
 
We do have some techniques where .NET framework does the job of catching exceptions in the worker threads as in the following.
  • Asynchronous delegates.
  • BackgroundWorker [Will discuss in upcoming articles].
  • TPL (Task Parallel Library) [Will discuss in upcoming articles].

So let’s see how we can handle worker threads exceptions in the main thread body using Asynchronous delegates.

  1. staticvoidDoWork()   
  2. {  
  3.     thrownewArgumentNullException();  
  4. }  
  5.   
  6. staticvoid Main(string[] args)   
  7. {  
  8.     Console.Title = "Threading Exception Handling Demo";  
  9.   
  10.     try   
  11.     {  
  12.         ActionMethodName = DoWork;  
  13.         IAsyncResult result = MethodName.BeginInvoke(nullnull);  
  14.         //Other code which can run in parallel  
  15.         MethodName.EndInvoke(result);  
  16.     } catch (Exception ex)   
  17.     {  
  18.         Console.WriteLine("Exception {0}", ex.Message);  
  19.     }  
  20. }  
Run the program in debug mode and you will see the result as in the following,

code

You can see in the above that the exception is getting caught in the parent try…catch block from where DoWork is called.

Hope you liked the article. Looking forward for your comments/suggestions.

 


Similar Articles