I'm tweaking some code in a RationalNumber
implementation. In particular, inside the equality logic, I'm considering the following:
public bool Equals(RationalNumber other)
{
if (RationalNumber.IsInfinity(this) ||
RationalNumber.IsInfinity(other) ||
RationalNumber.IsNaN(this) ||
RationalNumber.IsNaN(other))
{
return false;
}
try
{
checked
{
return this.numerator * other.Denominator == this.Denominator * other.numerator;
}
}
catch (OverflowException)
{
var thisReduced = RationalNumber.GetReducedForm(this);
var otherReduced = RationalNumber.GetReducedForm(other);
return (thisReduced.numerator == otherReduced.numerator) && (thisReduced.Denominator == otherReduced.Denominator);
}
}
As you can see I'm using exceptions as a flow control mechanism. The reasoning behind this is that I do not want to incurr in the penalty of evaluating the greatest common divisor of both fractions on every equality check. Thus I only decide to do it in the least probable case: one or both cross products overflow.
Is this an acceptable practice? I've always read that exceptions should never be used as a flow mechanism of your code, but I don't really see another way to achieve what I want.
Any alternative approaches are welcome.