c# - 为什么在调用者而不是有问题的行上抛出异常

标签 c# .net visual-studio debugging exception

我有一个简单的程序:

class Program
{   
    static void Main(string[] args)
    {
        Run().Wait();
    }

    private static async Task Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

Run() 方法被有意设计为抛出 NullReferenceException。困扰我的是为什么在线上抛出异常

Run.Wait()

而不是

someVariable.Replace(",",".");

实际异常在 InnerException 中可用 - 为什么?我失去了调试上下文,因为在 Run 方法之外抛出了异常。 enter image description here

如果我的程序是同步的:

class Program
{
    static void Main(string[] args)
    {
        Run();
    }

    private static void Run()
    {
        string someVariable = null;
        someVariable.Replace(",", ".");
    }
}

异常在正确的行抛出。为什么异步会破坏这个?

最佳答案

当您调用 Run.Wait() 时,Run() 方法抛出空异常然后 Wait方法将抛出 AggregateException。顺便说一句,你不会失去你的背景。如果点击[View Details],查看当前异常的InnerExceptionStackTrace,可以发现异常来自>Run()方法:

enter image description here

关于c# - 为什么在调用者而不是有问题的行上抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51944959/

相关文章:

c# - 我如何调查终结队列和终结幸存者

c# - CA2227 的解决方案或更好的方法?

C# - 确定 List<T> 是否脏?

c# - UWP 使用 JSON 数据创建列表

c# - 'RestSharp.IRestResponse`1<T0>' 在未引用的程序集中定义

c# - 解析 T-SQL 语句

.net - 来自 .ashx 文件的响应重定向

c# - VS17 安装 : Bootstrapper has stopped working

c++ - 在内部 while 循环中使用 EOF 时结束的 while 循环

c# - MSTest 抽象类