C# 为什么在调用方而不是问题行上引发异常
我有一个简单的程序:C# 为什么在调用方而不是问题行上引发异常,c#,.net,visual-studio,debugging,exception,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()方法故意设计为引发NullRefe
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方法之外抛出的。
如果我的程序是同步的:
class Program
{
static void Main(string[] args)
{
Run();
}
private static void Run()
{
string someVariable = null;
someVariable.Replace(",", ".");
}
}
在正确的行上引发异常。为什么async会破坏这一点?当调用Run.Wait()时,Run()方法引发了一个null异常,然后该方法将引发AggregateException。顺便说一句,你不会失去你的背景。如果单击[查看详细信息]并查看当前异常的InnerException的StackTrace,可以发现异常来自Run()方法:
@Nhan-Phan说的是真的 还有另一种处理此问题的方法: 您可以使用
.GetAwaiter.GetResult()
而不是使用.Wait()
,这也将打开AggregateException
如果您使用的是C#7.1,则可以使用
异步void Main
和wait
您的运行
方法可能的重复不会“丢失上下文”。该内部异常的StackTrace
准确地告诉您错误的起源。请尝试GetAwaiter().GetResult()
,而不是Wait()
,它应该在没有AggregateException的情况下抛出inline。当我谈到丢失上下文时,我的意思是,当异常抛出时,我不能检查Run方法的局部变量的内容。