Using OutOfBoundsException for non-arrays

Let's say I have a method that takes values ​​from 0 to x. If the parameter is greater than x or less than zero, I want to throw an exception. Is there a OutOfBoundsExceptionreasonable throw exception?

http://php.net/manual/en/class.runtimeexception.php says that it is "An exception is thrown if the value is not a valid key." Since I do not use this exception with arrays (henceforth keys), anyway, if I use it?

I mean, on the one hand, it does not seem to matter much. For example, if I chose an exception BadMethodCallException, and the person using this method knew that he either caught it, or for Exception, it seems that this will be enough, but it would be nice to have exceptions that also make sense.

+4
source share
2 answers

It should be good and appropriate to use for something like that. Exceptions are usually not related to their initial use. This is “out of bounds” as out of range of acceptable values, therefore it makes sense.

+2
source

Of the predefined SPL exceptions, I would prefer InvalidArgumentException. However, its documentation says:

An exception is thrown if the argument does not match the expected type.

. : UnexpectedValueException

, . , , , , .

"...", .

, , , . , BadMethodCallException, , , , , Exception, , , , .

. , . RuntimeException SPL.

+2

Source: https://habr.com/ru/post/1598478/


All Articles