InvalidArgumentException
The exception for an invalid function argument.
Syntax
new InvalidArgumentException(string $message = "")Parameters
| Parameter | Type | Description |
|---|---|---|
| $message | string | Optional. The error message. |
Return value
InvalidArgumentExceptionAn exception object.
Examples
Validating an argument:
<?php
function setAge(int $age): int
{
if ($age < 0) {
throw new InvalidArgumentException('Age cannot be negative');
}
return $age;
}
try {
setAge(-5);
} catch (InvalidArgumentException $error) {
echo $error->getMessage();
}Output:
Age cannot be negativeNotes
PHP has a set of ready-made exceptions for different cases: RuntimeException, LogicException, OutOfRangeException, JsonException. A fitting class makes an error clear without reading the message.
See also
- Exception — The base class of exceptions.
In the tutorial
- Exceptions — Exceptions in PHP — throw, try, catch and finally, custom exception classes and built-in errors.