Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return null for a 'float method' - Error handling

I want to put some error handling in my code. I can not figure out how to do it for following example:

public class DataPoints
{
   public PointF[] RawData {get; set;} //raw measurement pairs
   public float xMax; //max value on X axis
   public float yMax; //max value on Y axis

   public float GetMaxX()
   {
       if(RawData == null)
       {
          throw new NullReferenceException();
          return null; //THIS does not compile! I want to exit the method here
       }

     //DO other stuff to find max X
     return MAX_X; //as float
   }
}

So the idea is, I need to check if RawData is already set then do the rest of stuff in GetMaxX() method. Is this a good practice at all? What would you do in this case?

like image 613
Saeid Yazdani Avatar asked Dec 31 '25 13:12

Saeid Yazdani


1 Answers

There are two issues with this code,

First off you're throwing an exception, followed by a return - the return statement will never be hit as the exception will stop execution of the rest of the method, making the return statement superfluous.

Secondly, you can't return null when the return type is float; you'd have to change the return type to be float? (see: nullable types)

So either, if it is a real error case, as there is nothing you can do go with just the exception:

   public float GetMaxX()
   {
       if(RawData == null)
          throw new NullReferenceException();

     //DO other stuff to find max X
     return MAX_X; //as float
   }

Or alternatively, return the null and drop the exception:

   public float? GetMaxX()
   {
       if(RawData == null)
          return null; 

     //DO other stuff to find max X
     return MAX_X; //as float
   }

Personally, if RawData being null is an error condition / exceptional circumstance that should never happen then I would say throw the exception, and handle the exception if thrown in the calling code.

An alternative approach would be to force initialisation of RawData through the constructor, make RawData private (or at least the setter) and throwing the exception there. Leaving any other logic within the class clean of any exception throwing / null-checking as it can assume that RawData will have been set previously.

Resulting in something along the lines of:

public class DataPoints
{
    private readonly PointF[] rawData; //raw measurement pairs
    public float xMax; //max value on X axis
    public float yMax; //max value on Y axis

    public DataPoints(PointF[] rawData)
    {
        if (rawData == null)
            throw new ArgumentNullException("rawData");

        this.rawData = rawData;
    }

    public float GetMaxX()
    {
        //DO other stuff to find max X
        return MAX_X; //as float
    }
}
like image 118
Johannes Kommer Avatar answered Jan 02 '26 03:01

Johannes Kommer