views:

272

answers:

2

Hi everybody,

at the moment I am trying some of the new Features of the Task Parallel Library, shipped with the .Net Framework 4.0 Beta 2.

My question relates specifically to the Exception Handling within the TPL as described here: http://msdn.microsoft.com/en-us/library/dd997415%28VS.100%29.aspx

First example (changed it a little bit):

    static void Main(string[] args)
    {
        var task1 = Task.Factory.StartNew(() =>
        {
            throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
        });

        try
        {
            task1.Wait(); // Exception is not handled here....
        }
        catch (AggregateException ae)
        {
            foreach (var e in ae.InnerExceptions)
            {
                Console.WriteLine(e.Message);
            }

        }

        Console.ReadLine();
    }

According to the documentation the Exception should be propagated back to the to the joining thread which calls: task1.Wait().

But I always get an Unhandled Exception within:

var task1 = Task.Factory.StartNew(() =>
{
    throw new MyCustomException("I'm bad, but not too bad!");
});

Could someone explain to me why, or does someone know if there has sth. changed since the release of Beta 2?

+1  A: 

Your exception is probably being thrown before you ever reach the try statement, and the corresponding wait.

Try this:

static void Main(string[] args)
{

    try
    {   
        // Move this inside teh try block, so catch can catch any exceptions thrown before you get to task1.Wait();
        var task1 = Task.Factory.StartNew(() =>
        {
            throw new Exception("I'm bad, but not too bad!"); // Unhandled Exception here...
        });

        task1.Wait(); // Exception is not handled here....
    }
    catch (AggregateException ae)
    {
        foreach (var e in ae.InnerExceptions)
        {
            Console.WriteLine(e.Message);
        }

    }

    Console.ReadLine();
}
Reed Copsey
Unfortunately, this changes nothing in the behavior, there is still the Unhandled Exception as described above.
cap_Chap
+1  A: 

The answer is in the article you linked:

When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue and see the exception-handling behavior that is demonstrated in these examples. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

Strilanc