Search This Blog

Friday, January 22, 2010

C# Threading / MultiThreading - Exception Handling

Once a thread starts executing, all the Try-catch blocks in scope when was thread is created are of no relevance. So inorder to catch an exception, we have to catch it in the thread method itself.
Consider the example below:

public static void Main()
{
try
{
Thread worker = new Thread (Job);
worker.Start();
}
catch (Exception ex)
{
// THIS WILL NEVER EXECUTE
Console.WriteLine ("Exception occured");
}

static void Job()
{
throw new Exception();
}

}

In the above snippet, the function "Job" in worker thread throws an exception. But since there is no try catch in the the "Job" function, thus this exception will not be handled.

Inorder to handle this exception, we will need to add try catch to the "Job" function:

public static void Main()
{
try
{
Thread worker = new Thread (Job);
worker.Start();
}
catch (Exception ex)
{
// THIS WILL NEVER EXECUTE
Console.WriteLine ("Exception occured");
}

static void Job()
{
try
{
throw new Exception();
}
catch(Exception ex)
{
Console.WriteLine("Exception will be handled now");
}
}

}

Points to keep in Mind:
1. Global Exception Handler used in windows forms like
Application.ThreadException += LogError;
will not be able to catch exceptions when the exceptions occur in a thread method not wrapped in its try catch block.

2. AppDomain.UnhandledException event handler provided by Windows forms will be able to log the error but not help us in saving from getting the application down with error if exceptions occur in a thread method not wrapped in its try catch block.

No comments:

Post a Comment