可能获得有关 Null Reference Exception 的更多详细信息?

Possible to get more detail on Null Reference Exception?

我接管了一个遗留应用程序,我们正在逐步更新它。然而,有几大块代码被 try catch 包围。

偶尔调试的时候会出现空引用异常。最通用的“对象引用未设置为对象的实例”。这可能是 1000 行遗留代码内的任何内容。

是否有任何可能的方法来获取有关发生此异常的行的更多详细信息?

在 try catch 中包围时,堆栈跟踪仅指向异常块开始的行。

如何获取异常以显示失败的确切行?

如果您只是查找行号,可以从 Exception.StackTrace.

中获取

StackTrace class 表示堆栈跟踪,它是一个或多个 stack frames

的有序集合

例如:

try
{
    throw new Exception();
}
catch (Exception exception)
{

    var stackTrace = new StackTrace(exception, true);
    var frame = stackTrace.GetFrame(0);
    var line = frame.GetFileLineNumber(); // now you've got the line
}

此外,您可以在调试时使用调用堆栈 window,这有助于调试异常和一般 debugging