Home > Mobile >  Why does it show "possible null reference" warning when I have handled the ArgumentExcepti
Why does it show "possible null reference" warning when I have handled the ArgumentExcepti

Time:09-13

The exact warning I get is

Possible null reference argument for parameter 's' in 'double double.Parse(string s)

try
{
    // this is the line where it shows the warning as `input` can be null:
    double grade = double.Parse(input);

    book.AddGrade(grade);
}
catch (ArgumentException ex)
{
    System.Console.WriteLine(ex.Message);
}

Isn't the ArgumentNullException that the parse function can throw comes under the ArgumentException and thus should be handled?

Also I know TryParse can also be used but as a complete beginner I'd like to know what I'm doing wrong.

CodePudding user response:

C# compiler produces warning at that line because argument of Parse is marked as "non-nullable" and the compiler determined that the parameter input you are passing to that call can be null at the point of call. Compiler does not consider exception handling as a way to "safely handling null arguments" - instead it tries to guide you to avoid exceptions in a first place.

In this particular case it looks like you expect non-parseable values to be in input there is specific method - TryParse that makes handling of all invalid inputs (including null) uniform (returning false). In other cases you should either handle null values explicitly or review and potentially adjust the preceding/calling code to make it clear to the compiler (and more importantly to human readers of the code) that null can't reach the line in question.

Side note: generally, Using exceptions for flow control (which is what the code shown in the post doing) considered anti-pattern and should be avoided.

  • Related