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,
- Threading Simplified: Part 1
- Threading Simplified: Part 2
- Threading Simplified: Part 3
- Threading Simplified: Part 4
- Threading Simplified: Part 5
Let’s start with a simple example to understand the concepts.
- staticvoidDoWork()
- {
- thrownewArgumentNullException();
- }
- staticvoid Main(string[] args)
- {
- Console.Title = "Threading Exception Handling Demo";
- try {
- newThread(DoWork).Start();
- } catch (Exception ex)
- {
- Console.WriteLine("Exception {0}", ex.Message);
- }
- }

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,

So now we figured out that we need to put try..catch block in each worker threads method in order to catch their exceptions.
- 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.
- staticvoidDoWork()
- {
- thrownewArgumentNullException();
- }
- staticvoid Main(string[] args)
- {
- Console.Title = "Threading Exception Handling Demo";
- try
- {
- ActionMethodName = DoWork;
- IAsyncResult result = MethodName.BeginInvoke(null, null);
- //Other code which can run in parallel
- MethodName.EndInvoke(result);
- } catch (Exception ex)
- {
- Console.WriteLine("Exception {0}", ex.Message);
- }
- }

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.


Prakash TripathiTOP 100Posted Nov 6, 2016, 7:25 AM EST
@Daniele Arrighi, If you call new method from main in a new thread, it will not caught in main because main and new method are running in different thread. btw this article is still active.
Daniele ArrighiPosted Oct 25, 2016, 2:13 AM EDT
Does not catch the exception in the main thread. Maybe this article is too old?
Prakash TripathiTOP 100Posted Dec 28, 2015, 1:11 AM EST
Thnx Sibeesh
Prakash TripathiTOP 100Posted Dec 28, 2015, 1:11 AM EST
Thnx Gowtham.
Sibeesh VenuTOP 100Posted Dec 28, 2015, 12:27 AM EST
Nice Share
Gowtham RajamanickamTOP 100Posted Dec 28, 2015, 12:12 AM EST
Good One
Humayun Kabir MamunPosted Dec 27, 2015, 6:02 PM EST
Nice...