简体   繁体   中英

Exception not caught in Async / Await block

I'm just learning to use async / await in a windows Forms application, trying to keep my windows application responsive while doing slow actions. I see a difference in the handling of thrown exceptions.

If I use WebClient.DownloadStringTaskAsync, exceptions are caught by 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 an 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 Correct Way to Throw and Catch Exceptions using async/await someone advised to "disable 'Just My Code' in Tools->Options->Debugging->General"

After comments from Daniel Hilgarth (thanks Daniel!), I saw a copy - paste error. I've corrected it here. The problem still remains, but if you follow the advise to disable "just my code", the exception is properly caught.

So I guess the question is solved.

The problem is this:
You are throwing Exception but catching WebException .

Two solutions:

  1. Throw a WebException
  2. Catch a Exception

Solution 1 is preferred because you actually should never throw the unspecific Exception .

You're throwing a type Exception but only catching the more specific WebException . Catching WebException will only catch exceptions of type WebException or a type derived from it.

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