Search code examples
c#exception.net-4.0task-parallel-librarycontinuewith

How to catch an Exception that has been thrown in the ContinueWith part of a task?


On a button_click event, I start a Task to do some time consuming calculations asynchronously. I use Task.ContinueWith and set the TaskSheduler for the continuation to the UI synchronization context to display the result of the asynchronous calculations in a Textbox.

Now lets say this last part throws an Exception like this:

private void button1_Click(object sender, EventArgs e)
{
   Task.Factory.StartNew(DoSomeCalculations).ContinueWith
      (t => { throw new Exception("Some Exception"); }, TaskScheduler.FromCurrentSynchronizationContext()); 
}

If I enable the debug option "Enable Just My Code" then the program halts and I get a warning: "Exception was unhandled by user code"

But if I don't set this option, the Exception disappears in nowhere (no program crash, just nothing).

So how/where can I handle this Exception?

Edit: Please note, as the tag suggests, I'm using .NET-4.0


Solution

  • If you want to handle the exception then either have a try/catch block inside the continuation itself, so that it handles its own exceptions or add an additional continuation to the continuation to handle exceptions.

    Note that if you use await rather than ContinueWith to add continuations it's typically simpler, particularly when dealing with exceptions, as it will add the continuations on your behalf.