简体   繁体   中英

C# Handling Exception in Task with await

I'm new to the async and await keywords in C# and I am using C# 6.0. What is the problem with my code? The DivideByZeroException does not get caught in the catch block. I read that in C# 5 and newer, exceptions can be handled easily with using await keyword surrounded by a try-catch block.

private async void button1_Click(object sender, EventArgs e)
{
    try
    {
        Console.WriteLine("in try");                
        int result = await f(0);
        textBox1.Text = result.ToString();
    }
    catch (Exception)
    {
        Console.WriteLine("in catch");                
    }
    finally
    {
        Console.WriteLine("in finally");                
    }
}

Task<int> f(int x)
{
    return Task<int>.Factory.StartNew(() =>
    {
        return 10 / x;                
    });

}

It is working in release, but since this is WebForms / WPF or WinForms app, it doesn't have console, so Console.WriteLine never prints anything. Replace:

Console.WriteLine("in catch");

with

textBox1.Text = "in catch";

This will work:

try
{
    textBox1.Text += "in try";               
    int result = await f(0);
    textBox1.Text = result.ToString();
}
catch (Exception)
{
    textBox1.Text += "in catch";                
}
finally
{
    textBox1.Text += "in finally";                
}

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