Saturday, May 16, 2009

Bubbling Exceptions in Threads

Bubbling the exception from the thread is altogether different from bubbling the exception.

In normal scenario, we will bubble the exception just by throwing the exception in the catch block, but if you do so in the multi thread applications these exceptions will be lost in transition.

public void Main()
{
try{
Thread MyThread = new Thread(new ThreadStart(ThreadMethod));
MyThread.Start();

MyThread.Join();
Console.Writeline("Completed Without Errors");
}catch (Exception ex){
Console.Writeline(ex.ToString());
throw;
}
}

private void ThreadMethod()
{
try{
Thread.Threading.Sleep(10000);
throw new Exception("Generated Error");
}
catch(Exception){
throw;
}
}

The exception generated in the ThreadMethod() won't be caught in the Main() catch block, rather it will print the statement "Completed Without Errors" in the console window. Because of the following reason, in the ThreadMethod() once the exception is generated and bubbled, but in the due course of time when it reaches the Main() method. Status of "MyThread" is completed and the it is removed from the memory.

Then, how to bubble the exception effectively to the calling program. In this case we need to assign the exception to the common variable and check the status in the Main() method.  



public class MyClass(){

Exception _ThrdMtdExp=null;

public void Main()

{
try{
_ThrdMtdExp =null;
Thread MyThread = new Thread(new ThreadStart(ThreadMethod));
MyThread.Start();
MyThread.Join();
if (_ThrdMtdExp!=null)
throw new Exception("Exception Raised by ThreadMethod()",_ThrdMtdExp);
else
Console.Writeline("Completed Without Errors");
}catch (Exception ex){
Console.Writeline(ex.ToString());
throw;
}

}

private void ThreadMethod()
{
try{
Thread.Threading.Sleep(10000);
throw new Exception("Generated Error");
}
catch(Exception ex){
_ThrdMtdExp = ex;
}
}
}

Now, the Main() method will capture the exception occured in the ThreadMethod().