What type of exception should I throw?
I have a console class which describes rectangle of cells which a user can index by passing in a coordinate:
width, height = 80, 25 console = Console.new(width, height) x, y = 2, 5 point_on_screen = Point.new(x, y) console[point_on_screen] = 'a'
I am now wondering what types of exception to throw when an index occurs out of bounds . That is, outside of the (constant!) domains x:[0, width] and y:[0, height]. I could throw a
RangeError or an
- Does it matter which type of exception to throw as long as the error message is useful?
- Should I use the same exception type for both the construction of the console and the indexing? Are the two really semantically different?
* returning a kind of out of bounds object is possibly a better option - something like a Null Object Pattern - but not what I am wondering about here.
One option is to throw an
ArgumentError because the argument is obviously wrong, dimensions can never be non-negative. This is what I throw in example 1, because we ought to know in advance that the dimensions should be non-negative.
console = Console new(-3, 4) # Argument error
Another option is to throw a
RangeError because the argument is out of the valid range. I use these for indexing. The argument is always out of range if x < 0, but if x ≥ 0 then it depends on the width of the console if the x is in the domain.
console = Console.new(20, 40) pt = Point.new(-3, 4) Console[pt] # RangeError