Wednesday, September 28, 2011

How to handle exceptions while working with Threading?


Everybody knows how to handle exception in application using try catch and finally block. In this post I will explain how handle exception while working with Threading. Multiple threads can run inside single process parallelly. WPF and Winforms application runs on UI Thread and handled only exception which are thrown from the main thread. So when you create new Thread from application and the calling method throws an exception which is not handled by main UI Thread.

Let’s understand using simple example.

public static void Main()
{
    try
    {
        Thread thread = new Thread(new ThreadStart(DisplayName));
        thread.Start();
    }
    catch (DivideByZeroException ex) //Exception will not handled here
    {
        MessageBox.Show(ex.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
public void DisplayName()
{
    int a = 0;
    int b = 10 / a; //throws unhandled exception
}

As per above code snippet, method DisplayName throws DivideByZeroException but it will not handled by the try catch block written inside Main() method and application shows unhandled application. Keep in mind that each thread has its own independent execution path. Let’s have a look on below code and see how to overcome with this scenario.

public static void Main()
{
    Thread thread = new Thread(new ThreadStart(DisplayName));
    thread.Start();
}

public void DisplayName()
{
    try
    {
        int a = 0;
        int b = 10 / a;
    }
    catch (DivideByZeroException ex)
    {
        MessageBox.Show(ex.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

In above code, exception is handled on DisplayName method and user can see the correct error message box showing exception information. So now exception is handled within or inside thread execution path and this is the effective way to handling exception with threading.

Hope you liked this tip and also know correct way to handle exception while working with threading.

See also - 

1 comment:

  1. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training institute in velachery

    ReplyDelete