FAQ :: The Debugger does not correctly handle Task exceptions?

FAQ :: The Debugger does not correctly handle Task exceptions?

  • Comments 2

The following code correctly observes and handles a Task exception and should print “gotcha!” to the console.  By default though, the Debugger will report a crash.

Task t = Task.Factory.StartNew(() => { throw new Exception("poo"); });

try { t.Wait(); }

catch (AggregateException) { Console.WriteLine("gotcha!"); }


The issue has to do with the “Just My Code” mode (enabled by default), which causes the Debugger to break in immediately when an exception leaves user code (the Task delegate) and enters non-user code (TPL internal).  This is usually a good thing, because it allows you to pinpoint exactly where an exception is going unhandled.  However, in this case, the Debugger is breaking before TPL can observe the exception.

Running without debugging or disabling “Just My Code” (Tools -> Options -> Debugging -> General) should resolve the issue.  Also, note that the Debugger actually broke in as though it had hit a breakpoint, so Continuing (F5) or Stepping (F10/F11) should allow further execution.

Just My Code Mode

Attachment: just-my-code.png
Leave a Comment
  • Please add 4 and 7 and type the answer here:
  • Post
  • I too have same problem.

    But the solution did not work. however if I try pressing F5/ F11 then I am getting the expected result(Catching exception)

  • Excellent, nice one. Was wondering what the *** was going on.

Page 1 of 1 (2 items)