20

I have the following code:

Task load = Task.Factory.StartNew(() => {//Some Stuff Which Throws an Exception});

try
{
    load.Wait();
}
catch (AggregateException ex)
{
    MessageBox.Show("Error!");
}

Whenever an exception is thrown in the Task, I want it to bubble up and get caught in the try catch instead of Visual Studio breaking at the point the exception is caused.

I tried Google and some suggested I add this [DebuggerHidden] on top of my method, but it doesn't work.

Pang
  • 9,564
  • 146
  • 81
  • 122
Krimson
  • 7,386
  • 11
  • 60
  • 97
  • 1
    Oh, man, this so confused me. I thought my exception wasn't being caught at all, but rather the automatic breaking is just premature and can be continued from. Really seems like a very bad default behavior. The error message seems blatantly wrong, since it claims the exception was uncaught but continuing will cause it to be caught perfectly fine. – Kat Jun 23 '15 at 19:35

3 Answers3

32

Ok I found out how to do it. The answer is right here in the note section

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 Enable Just My Code checkbox under Tools, Options, Debugging, General.

Krimson
  • 7,386
  • 11
  • 60
  • 97
9

From the point of view of VS, there really isn't any difference between the exception being thrown from within a delegate passed to a Task from any other exception.

There is no way to solve this in the general case.

However, the one thing that you could do is leverage the fact that when the exception is re-thrown, it's wrapped in an AggregateException. You could break when an AggregateException is thrown but not other exceptions.

You can go to Debug -> Exceptions, unselect all CLR exceptions, but then re-enable aggregate exceptions:

enter image description here

It will now not pause in the Task body but will pause the debugger when you call Wait.

The unfortunate side effect is that you'll now no longer pause for any other exceptions anywhere else in your program, even if they're not in a delegate passed to a Task.

Pang
  • 9,564
  • 146
  • 81
  • 122
Servy
  • 202,030
  • 26
  • 332
  • 449
1

To turn off stop on exceptions press " Ctrl + Alt + E ". This will open the Exceptions window . Untick "Common Language Runtime Exceptions - Thrown".

pingoo
  • 2,074
  • 14
  • 17
  • 1
    That would prevent it from pausing from within the delegate, but not when it's rethrown on `Wait`. – Servy Jun 04 '13 at 15:47
  • For me, this was the solution I was looking for. To stop VS from breaking inside a try when debugging. Thanks – MartinS Jul 10 '22 at 20:14