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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With