Exception did not fall into Async / Await block

I just learned how to use async / await in a Windows Forms application, trying not to respond to a Windows application when doing slow actions. I see a difference in exception handling.

If I use WebClient.DownloadStringTaskAsync, the exceptions get into my code:

private async void button1_Click(object sender, EventArgs e)
{
  try
  {
    this.textBox1.Text = await webClient.DownloadStringTaskAsync("invalid address");
  }
  catch (Exception exc)
  {
    textBox1.Text = exc.Message;
  }
}

However, if I call the async function in my own code, the exception is not caught:

private string GetText()
{
  throw new Exception("Tough luck!");
}

private async void button3_Click(object sender, EventArgs e)
{
  using (var webClient = new WebClient())
  {
    try
    {
      this.textBox1.Text = await Task.Run(() => GetText());
    }
    catch (Exception exc)
    {
      textBox1.Text = exc.Message;
    }
  }
}

As an answer to the stackoverflow question The correct way to throw and catch exceptions using async / await , someone suggested "disable" Only my code "in Tools-> Options-> Debugging-> General"

( !), - . . , " ", .

, , .

+4
2

:
Exception, WebException.

:

  • WebException
  • Exception

1 , Exception.

+3

Exception, WebException. WebException WebException , .

+1

All Articles