InexactError vs OverflowError

I have a number type which throws when the result of a binary operation like + or * is not representable in this type. I think InexactError is the right choice of exception, while OverflowError seems like a bad choice because it seems like exposing implementation details. Or should OverflowError perhaps be considered as a more specific InexactError?

My type basically wraps Int, so the two simplest implementations could look like this, assuming we’re implementing the binary * method:

  • Int(widen(a) * b)  # may throw `InexactError` if the `widen(Int)` value doesn't fit into `Int`
    
  • Base.checked_mul(a, b)  # more efficient (?), but may throw `OverflowError` in case of overflow
    
  • a third option could be to use Base.mul_with_overflow(a, b), then throw and choose exception type explicitly

Questions:

  • How to choose between InexactError and OverflowError, in general?
  • Does a legitimate motivation for using OverflowError even exist? Should we just always use InexactError instead?
  • Which of the three implementations above would you use? Or maybe you’d use some other implementation?

In Base at least, I believe that InexactError is only used for conversions, which feels different from this. Then again I’m not clear that it’s an overflow in your case either… need a little more detail.

1 Like

Ended up going with OverflowError, this is the PR:

Thanks, that makes sense, and I guess it justifies the choice I went with.

1 Like

I don’t know if this was ever the intent, but my expectation as a user is that I could get around an OverflowError in an operation by using a similar type with more bits, e.g. Int64 gets me more integer values than Int32, but an InexactError is a fundamental inability of the type to convert another type’s values e.g. Int64(1im), Int128(3.5), Int8(300). It’s a bit of a misnomer because it’s not about losing precision in rounding, Float32(1.2321976518237652) silently does that. There’s probably some proper mathematical way of describing the values’ subsetting that distinguishes these.

4 Likes