Question

This is a sample code from a "C# 5.0 in a Nutshell"

TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
Task.Factory.StartNew (() =>
{
    Task.Factory.StartNew (() => { throw null; }, atp);
    Task.Factory.StartNew (() => { throw null; }, atp);
    Task.Factory.StartNew (() => { throw null; }, atp);
})
.ContinueWith (p => Console.WriteLine (p.Exception),
                TaskContinuationOptions.OnlyOnFaulted);

I have a "CLR exceptions": "break on user-unhandled" option checked in my VS2012 settings and running this code provides a VS's "NRE exception was unhandled by user code" popup on the throw null;

I've tried to try-catch exception on Wait in the ContinueWith and later but still got the unhandled exception.

I feel like a solution with turning "CLR exceptions": "break on user-unhandled" off seems wrong, because I actually handle this exception. So what is the right way to manage it?

Was it helpful?

Solution

The reason for the debugger stopping execution is that "Break on user-unhandled exceptions" will break on any exception that is not handled by a handler in user code ("My Code").

Since the TPL, which is the one catching the exception, is not considered user code, the debugger will consider the exception unhandled by user code.

The problem is, the TPL does not have any other way to trigger TaskContinuationOptions.OnlyOnFaulted, so I'm afraid you're probably stuck seeing the exceptions.

Hopefully, getting exceptions isn't part of your normal flow. If it's not, seeing the exceptions as unhandled in the debugger may actually be a good thing for debugging errors in your task flow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top