-2

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;                
    });

}
FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
  • 1
    @CodeCaster while it looks similar, I don't think it's a duplicate. – Evk Feb 20 '18 at 13:39
  • I can't reproduce the issue (at least in LinqPad). It prints "in try", "in catch" and "in finally". Have you tried putting a breakpoint in the catch block to see if it really is not entered? – ckuri Feb 20 '18 at 13:46
  • @ckuri yes, you are right. I checked again. but the exception just get catched in release mode. in debug mode will not enter catch block! why?! – Hamid Reza Arzaghi Feb 20 '18 at 13:53

1 Answers1

0

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";                
}
FCin
  • 3,804
  • 4
  • 20
  • 49
  • Is there a way to enter the catch block in Debug mode? – Hamid Reza Arzaghi Feb 20 '18 at 14:57
  • @HamidRezaAZ It will enter catch and after that finally block in both release and debug. Make sure you append text not replace it or just remove textBox1 from finally block – FCin Feb 20 '18 at 15:33