CodeQL 文档

不良错误处理:捕获 NullReferenceException

ID: cs/catch-nullreferenceexception
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - reliability
   - correctness
   - external/cwe/cwe-395
Query suites:
   - csharp-security-and-quality.qls

单击以在 CodeQL 代码库中查看查询

不应将捕获 NullReferenceException 作为检查和断言的替代方法来防止取消引用空指针。

建议

在取消引用变量之前检查它是否为 null。

示例

以下示例类 findPerson 在找不到人员时返回 null。

class CatchOfNullReferenceException
{
    public static Person findPerson(string name)
    {
        // ...
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Enter name of person:");
        Person p = findPerson(Console.ReadLine());
        try
        {
            Console.WriteLine("Person is {0:D} years old", p.getAge());
        }
        catch (NullReferenceException e)
        {
            Console.WriteLine("Person not found.");
        }
    }
}

以下示例已更新,以确保正确处理任何 null 返回值。

class CatchOfNullReferenceExceptionFix
{
    public static Person findPerson(string name)
    {
        // ...
    }

    public static void Main(string[] args)
    {
        Console.WriteLine("Enter name of person:");
        Person p = findPerson(Console.ReadLine());
        if (p != null)
        {
            Console.WriteLine("Person is {0:D} years old", p.getAge());
        }
        else
        {
            Console.WriteLine("Person not found.");
        }
    }
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私