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

c# – 从异步方法中捕获自定义异常,第1张

概述我正在尝试捕获异步方法中抛出的自定义异常,但由于某种原因,它总是被通用异常catch块捕获.请参阅下面的示例代码 class Program{ static void Main(string[] args) { try { var t = Task.Run(TestAsync); t.Wait(); 我正在尝试捕获异步方法中抛出的自定义异常,但由于某种原因,它总是被通用异常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}
总结

以上是内存溢出为你收集整理的c# – 从异步方法中捕获自定义异常全部内容,希望文章能够帮你解决c# – 从异步方法中捕获自定义异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1248025.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存