简体   繁体   中英

async try catch - exception variable is null

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

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 'line'这是一个“行”断点

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM