加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 从异步方法中捕获自定义异常

发布时间:2020-12-15 08:16:29 所属栏目:百科 来源:网络整理
导读:我正在尝试捕获异步方法中抛出的自定义异常,但由于某种原因,它总是被通用异常catch块捕获.请参阅下面的示例代码 class Program{ static void Main(string[] args) { try { var t = Task.Run(TestAsync); t.Wait(); } catch(CustomException) { throw; } catc
我正在尝试捕获异步方法中抛出的自定义异常,但由于某种原因,它总是被通用异常catch块捕获.请参阅下面的示例代码
class Program
{
    static void Main(string[] args)
    {
        try
        {
            var t = Task.Run(TestAsync);
            t.Wait();
        }
        catch(CustomException)
        {
            throw;
        }
        catch (Exception)
        {
            //handle exception here
        }
    }

    static async Task TestAsync()
    {
        throw new CustomException("custom error message");
    }
}

class CustomException : Exception
{
    public CustomException()
    {
    }

    public CustomException(string message) : base(message)
    {
    }

    public CustomException(string message,Exception innerException) : base(message,innerException)
    {
    }

    protected CustomException(SerializationInfo info,StreamingContext context) : base(info,context)
    {
    }
}

解决方法

问题是Wait抛出了一个AggregateException,而不是你想要捕获的异常.

你可以用这个:

try
{
    var t = Task.Run(TestAsync);
    t.Wait();
}
catch (AggregateException ex) when (ex.InnerException is CustomException)
{
    throw;
}
catch (Exception)
{
    //handle exception here
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读