-1

This code is merely for learning/test purpose:

I am deliberately throwing an Exception inside a Task.Run(...) and calling it from a WindowsForm ButtonClickEventHandler:

async void button_Click(object sender, EventArgs e)
{
    try
    {
        await Task.Run(
            () =>
            {
                throw new Exception("Foo");
            }
        );
    }
    catch (Exception ex) { }
}

When I debug the application and put a breakpoint to the catch statement, I see that the variable "ex" has the value null. Why is that and how can I capture the exception content? (If I use Task.Wait() or ContinueWith() afterwards it is captured correctly, but I want to know how to catch it when using await)

Here is the strange part: If I insert a "Debug.WriteLine(ex.Message);" statement inside the catch, ex is not null anymore. And if I remove the "Debug.WriteLine(ex.Message);" statement again and run the code ex is not null. Apparently on some runs ex has the value, sometimes it's just null.

Is that a Thread issue or is it just a Visual Studio bug?

Environment: Windows 10, VS 2019, .NET 5.0, Windows Forms Application

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
A.B.
  • 2,374
  • 3
  • 24
  • 40
  • Does this help you https://stackoverflow.com/questions/32067034/how-to-handle-task-run-exception? – ggeorge Mar 18 '21 at 19:54
  • 2
    Try putting a `Console.WriteLine(ex);` inside the catch-block. I'm sure it's not null if it actually enters the catch-block – Xerillio Mar 18 '21 at 19:54
  • @Xerillio: If I put a Debug.WriteLine(ex.Message) statement inside the catch, the message is displayed and variable "ex" is not null. But I still would like to know why in the first case VS is showing ex as null, despite the exception is caught properly. Is this a bug? – A.B. Mar 18 '21 at 20:03
  • 3
    @A.B. If I remember correctly, because there's no statements in your catch block, the debugger never really enters the scope of that code-block, so no variables for that scope are expanded. This is a good reminder to avoid swallowing exceptions with empty code-blocks - it's bad practice. – Xerillio Mar 18 '21 at 20:16

1 Answers1

4

The precise position of your breakpoint matters. If you just breakpoint the line, ex will be null. If you breakpoint the opening brace of the catch block, ex will have a value. You can also step past the line breakpoint onto the brace to get the value.

This is a breakpoint on the opening brace This is a breakpoint on the opening brace

This is a breakpoint on the 'line' This is a 'line' breakpoint

Kenneth Ito
  • 5,201
  • 2
  • 25
  • 44