NullReferenceException位置信息

本文关键字:信息 位置 NullReferenceException | 更新日期: 2023-09-27 17:52:38

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

NullReferenceException位置信息

几点建议:

  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
        }
    }