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
I guess the largest difference is "argument" vs "value".
The way I see it is that InvalidArgumentException
is for (passed) arguments, whereas UnexpectedValueException
applies to (returned) values.
Also there's a subtle but important difference between "invalid" and "unexpected" - which also explains why the first is LogicException and the second a RuntimeException.
For example: say i've got a function that utilizes the Twitter-api called: getLastMessageDate($userid)
:
You pass a (numeric) user-id and it returns the date of the last message of that user as yyyy-mm-dd string.
Now, suppose I call this function with a string as argument instead of a number. At this point I can call an InvalidArgumentException, because the provided argument is invalid for this function. These checks can be done by logic - because a variable is either numeric or it is not. Therefore it's a LogicException.
However, the return value of a function may not be verifiable by logic - especially when you're dealing with (third-party) dynamic content. Because you can never know exactly what your function is going to return. (if you would, this would arguably render your function useless.)
So, this time I call my function with a (valid) user-id and my function gets the date of the last message of that user. With this date I would like to do something, like some formatting.
Now imagine the guys at Twitter did something wrong and instead of my expected yyyy-mm-dd date-string, I get an empty string or a different string saying 'blaaaa'.
At this point, i can throw an UnexpectedValueException
.
I can't say that this value is "Invalid" - I asked for a string and I got a string. But it is however not the "kind of string" i was expecting: therefore Unexpected ValueException.
Hope this clears something up. This is my first post - so far I've learned that writing down what's in my head isn't the easiest thing (also English is not my native language).