【问题标题】:NullReferenceException location information? [duplicate]NullReferenceException 位置信息? [复制]
【发布时间】:2015-08-16 15:21:39
【问题描述】:

我有一个应用程序(已发布)和一个很少向用户弹出的 NullReferenceException,但我想处理它。我查看了其中的堆栈和方法,找不到它会发生的特定位置(这是一个相当大的方法/算法)。现在我只是用 try/catch 来围绕调用本身,但如果我能弄清楚情况,我想更好地处理它。
问题是,据我所知,NRE 无法提供代码中具体是什么导致它的线索。有没有办法获得行号或任何其他可能暗示原因的信息?

【问题讨论】:

标签: c# nullreferenceexception


【解决方案1】:

一些提示:

  1. 如果您将符号文件 (.pdb) 与可执行文件/dll 文件一起部署,那么您获得的堆栈跟踪将包括行号。
  2. 它还有助于将您的方法分解成更小的部分,以便您的堆栈跟踪可以让您更好地了解错误发生时您所处的位置。
  3. 您可以通过检查其输入中是否存在 null 或其他无效值来开始每个方法,以便您快速失败并提供有意义的消息。

    private void DoSomething(int thingId, string value)
    {
        if(thingId <= 0) throw new ArgumentOutOfRangeException("thingId", thingId);
        if(value == null) throw new ArgumentNullException("value");
        ...
    }
    
  4. 您可以用异常包装器包围每个方法,以便在堆栈跟踪的每个级别上提供更多信息。

    private void DoSomething(int thingId, string value)
    {
        try
        {
            ...
        }
        catch (Exception e)
        {
            throw new Exception("Failed to Do Something with arguments " +
                new {thingId, value},
                e); // remember to include the original exception as an inner exception
        }
    }
    

【讨论】:

    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多