Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in threads

Recently i have attended an interview . A code snippet is given to me.I know,the interviewer took it from albhari's threading sample.

public static void Main() 
{
    try 
    {
        new Thread (Go).Start();
    }
    catch (Exception ex)
    {
        // We'll never get here!
       Console.WriteLine ("Exception!");
    }
}

static void Go() { throw null; }

The modification of the above code as

public static void Main()
{
    new Thread (Go).Start();
}

static void Go() 
{
    try 
    {
        ...
        throw null; // this exception will get caught below
        ...
    }
    catch (Exception ex) 
    {
        Typically log the exception, and/or signal another thread
        that we've come unstuck
        ...
    }
}

would be the good candidate to handle the exception.

I have been asked, "Except the above trail what are the other alternatives would fit as good solution?. It was hard to find the alternative,so i raise it here to gather your suggestion.

like image 706
user184805 Avatar asked Oct 12 '09 12:10

user184805


2 Answers

There are alternatives listed on Joe Albahari's website: http://www.albahari.com/threading/#_Exception_Handling

"There are, however, some cases where you don’t need to handle exceptions on a worker thread, because the .NET Framework does it for you. These are covered in upcoming sections, and are:
-Asynchronous delegates
-BackgroundWorker
-The Task Parallel Library (conditions apply)"

like image 182
jrupe Avatar answered Oct 06 '22 00:10

jrupe


Exception thrown in a thread normally couldn't be caught in another thread.

You'd better to catch it in function Go and pass it to main thread explicitly.

However, if you just want to log all unhandled messages from all threads, you may use AppDomain.UnhandledException event or equivalent events at Application class if you are developing WinForms or WPF app.

like image 27
elder_george Avatar answered Oct 05 '22 23:10

elder_george