PHP Reference ยท Exceptions and Errors
PHP InvalidArgumentException class
Reference for PHP InvalidArgumentException: the SPL logic exception for bad argument values, how it compares to ValueError and TypeError, with examples.
InvalidArgumentException is an SPL exception you throw when a function receives an argument of the right type but an unacceptable value: a negative quantity, an empty name, a string that is not a known option. It extends LogicException, which signals a mistake in the calling code that could have been prevented by checking the input first.
The SPL logic family is LogicException and its children BadFunctionCallException, BadMethodCallException, DomainException, InvalidArgumentException, LengthException and OutOfRangeException. They are all ordinary Exception subclasses.
function setQuantity(int $n): void { if ($n < 1) { throw new InvalidArgumentException("Quantity must be at least 1, got $n"); } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
class InvalidArgumentException extends LogicException {} new InvalidArgumentException( string $message = "", int $code = 0, ?Throwable $previous = null );
| Name | Description |
|---|---|
$message |
Text describing which argument is wrong and what is allowed. |
$code |
Optional integer code for your own error numbering. |
$previous |
Optional earlier exception, kept for chaining. |
Usage notes
- Value versus type. A wrong type is a
TypeError, which PHP raises itself when you declare parameter types. A wrong value of the right type isInvalidArgumentExceptionin your own code. - Built-in functions use
ValueError. Since PHP 8.0 core functions such asstr_repeat()throwValueErrorfor bad values. Library code you write may use either;InvalidArgumentExceptionremains the common choice because it is anExceptionand is easy to catch with application errors. - Say what was expected. Include the argument name, the allowed range and the received value in the message.
- Validate early. Throw at the top of the function so no half-done work is left behind.
- Not for runtime failures. A missing file or a failed connection is a
RuntimeException, because correct arguments would not have prevented it. - Narrower siblings.
DomainExceptionis for values outside a domain,OutOfRangeExceptionfor an illegal index,LengthExceptionfor a bad length. UsingInvalidArgumentExceptionfor all of them is acceptable.