I am wondering if what i am going to do is good or bad thing. I have that class:
public class Element : IElement
{
public float? Max { get; private set; }
public float? Min { get; private set; }
public float? Average { get; private set; }
public bool HasValue { get; private set; }
public void SetRange(float? min, float? max)
{
if (min >= max)
{
throw new WrongElementValueException("Min must be greater than max!");
}
else if (min < 0f || max < 0f)
{
throw new WrongElementValueException("Min/max must be greater than 0!");
}
else if (min > 100f || max > 100f)
{
throw new WrongElementValueException("Min/max must be lesser than 0!");
}
else
{
Min = min;
Max = max;
Average = (min + max)/2f;
HasValue = true;
}
}
}
The user will set the values using SetRange() method. But he has some constraints like Min must be bigger than Max, and neither of them should be bigger than 100 or lesser than 0.
Should I use those exceptions in this place? Or is there any better method to handle wrong user input? I hope my question isn't to general.
This is an appropriate practice, yes.
Though I imagine consuming code would be expecting an ArgumentException
rather than this exception type, but that may be a relatively minor point.
When the input is invalid, and the object has no way of meaningfully continuing otherwise, then throwing an exception is an appropriate and expected response. It's up to consuming code to use the object properly, handle errors, report back to the user, etc.
The alternative is for this object to "try to figure out what to do" which often leads to some pretty bad coding practices. For example...
This object does one thing, and only that one thing. If it's invoked in such a way that it can't do that one thing, an exception is an expected and appropriate failure condition.
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