InvalidArgumentException vs UnexpectedValueException

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)