c# - 新的 .NET 运行时能否抛出更有意义的空引用异常?

标签 c# .net exception runtime c#-6.0

我们知道 .NET 运行时在抛出异常时不是很有帮助,因为它只显示一般消息,而不指示任何变量或参数名称。但它可以采用不同的方式吗?

例如在这种情况下:

class foo
{
    public void bar() {}
}

foo f = null;
f.var(); // NullReferenceException

但是从 C# 6 开始,如果我们使用新的 ? 运算符,编译器能够生成不同的代码,因此它能够检查 f 是否为空;

f?.var(); 

难道它不能像使用 时那样用类似的空检查来包装调用吗? 并获取 f 的名称并创建一条异常消息,例如

Additional information: Object reference "f of type Foo" not set to an instance of an object.

是否也可以将它用于其他异常类型并在其中放置有意义的信息,或者无论这意味着什么,它是否昂贵?

最佳答案

没有。如果可以的话,他们早就做到了。布拉德·亚当斯 has blogged about it back in 2004

The NullReferenceException occurs because an instruction like “call [eax+44]” or “mov edx, [esi+24]” has resulted in an access violation. We don’t retain nearly enough information to form a correspondence between a particular register being NULL at a particular EIP and the fact that a particular reference in the application was null. Especially since the EIP might be in a shared helper like a write barrier routine or an array helper. In those cases, we would have to perform a limited stack walk to get the effective EIP.

The machinery that would be required to improve this error message is huge. For the foreseeable future, you will have to rely on debuggers, or on FX code explicitly checking and throwing an appropriate NullArgumentException.

如您所见,可用于提供有意义的错误消息的信息非常少,而且创建机制也需要付出很多努力。您不太可能会在 .Net 中看到此功能。

关于c# - 新的 .NET 运行时能否抛出更有意义的空引用异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33514478/

相关文章:

c# - 我在使用 C# 中的多行正则表达式时遇到问题,我该如何解决?

.net - 匿名类型集合?

c# - 正则表达式无法区分 float 和 int 类型

java - 在 catch 子句中终止程序的良好做法是什么

c# - Rhinomocks - 模拟代表

c# - 无法使用 ASP.NET session 状态提供程序连接到 Redis 服务器

c# - Datagridview 在选择复选框时崩溃

c# - BCL 中的任何地方是否有一个(隐藏得很好的)通用枚举用于启用/禁用?

unit-testing - Unity 中的单元测试 - 获取 InvalidCastException - 为什么?以及如何解决?

security - ckeditor 3.0 仅包含在 HTTPS 页面上时会导致 "unauthenticated content"