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.
All right, but don’t we have any other way to catch the exceptions in the calling thread method body?
- 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 TripathiPosted Nov 6, 2016, 12:25 PM
@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, 6:13 AM
Does not catch the exception in the main thread. Maybe this article is too old?
Prakash TripathiPosted Dec 28, 2015, 6:11 AM
Thnx Sibeesh
Prakash TripathiPosted Dec 28, 2015, 6:11 AM
Thnx Gowtham.
Sibeesh VenuPosted Dec 28, 2015, 5:27 AM
Nice Share
Gowtham RajamanickamPosted Dec 28, 2015, 5:12 AM
Good One
Humayun Kabir MamunPosted Dec 27, 2015, 11:02 PM
Nice...