When should I use InvalidArgumentException and when UnexpectedValueException? They look the same to me.
Note that one extends LogicException and the other one extends RuntimeException, so the difference shouldn’t be so subtle IMO.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Looking closely at the descriptions on the manual pages:
InvalidArgumentException
(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
From this, we can conclude that
InvalidArgumentExceptionis intended to check types of arguments passed to a function, whileUnexpectedValueExceptionis 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 whichshould 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 leavesUnexpectedValueException(which extendsRuntimeException) as the only candidate in such cases.