Michas Michas - 1 year ago 91
PHP Question

PHP: What SPL exception should I do if a variable value is wrong?

There are two similar exception in php: the RangeException and the UnexpectedValueException. Both are subclasses of the RuntimeException. The problem is, I don't see much difference.


Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.


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.

I know it is a runtime error. If a variable type is wrong, it is simple, I should use the UnexpectedValueException.

What should I do if a variable value is wrong?

Answer Source

It looks it is the best to stay with the UnexpectedValueException.

  1. I haven’t found any convention.
  2. The unexpected value is a better descriptions for programmers.
  3. If there is a special recovery code, a custom exception would be better.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download