简体   繁体   English

异常未在Async / Await块中捕获

[英]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. 我只是学习在Windows窗体应用程序中使用async / await,尝试在执行慢动作时保持我的Windows应用程序响应。 I see a difference in the handling of thrown exceptions. 我看到抛出异常的处理有所不同。

If I use WebClient.DownloadStringTaskAsync, exceptions are caught by my code: 如果我使用WebClient.DownloadStringTaskAsync,我的代码会捕获异常:

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" 作为stackoverflow问题的答案使用async / await有人建议在工具 - >选项 - >调试 - >常规中“禁用'我的代码'

After comments from Daniel Hilgarth (thanks Daniel!), I saw a copy - paste error. 在Daniel Hilgarth的评论之后(感谢Daniel!),我看到了一个复制粘贴错误。 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 . 您正在抛出Exception但捕获WebException

Two solutions: 两种解决方案

  1. Throw a WebException 抛出WebException
  2. Catch a Exception 抓住Exception

Solution 1 is preferred because you actually should never throw the unspecific Exception . 解决方案1是首选,因为您实际上不应该抛出非特定的Exception

You're throwing a type Exception but only catching the more specific WebException . 您正在抛出一个Exception类型,但只捕获更具体的WebException Catching WebException will only catch exceptions of type WebException or a type derived from it. 捕获WebException只会捕获WebException类型的WebException或从中派生的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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