InvalidArgumentException vs UnexpectedValueException

后端 未结 3 918
我寻月下人不归
我寻月下人不归 2021-02-01 14:06

When should I use InvalidArgumentException and when UnexpectedValueException? They look the same to me.

Note that one extends LogicException and the other one extends Ru

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-01 14:27

    Looking closely at the descriptions on the manual pages:

    InvalidArgumentException

    Exception thrown if an argument is not of the expected type.

    (The description was Exception thrown if an argument does not match with the expected value. until mid-2014, but was changed when PHP 5.6 got introduced)

    UnexpectedValueException

    Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value[,] not including arithmetic or buffer related errors.

    From this, we can conclude that InvalidArgumentException is intended to check types of arguments passed to a function, while UnexpectedValueException is intended to verify values vs valid value sets, possibly during the internal computations of a function (e.g. values returned from other functions).

    Note that checking the values of arguments is kind of gray area here; arguably, since InvalidArgumentException extends LogicException, it should only handle situations which should lead directly to a fix in your code. Since throwing an exception in case of out-of-range input values can be a completely expected runtime behaviour, this leaves UnexpectedValueException (which extends RuntimeException) as the only candidate in such cases.

提交回复
热议问题