Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

InvalidArgumentException

The exception for an invalid function argument.

Syntax

new InvalidArgumentException(string $message = "")

Parameters

ParameterTypeDescription
$messagestringOptional. 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 negative

Notes

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

In the tutorial

  • Exceptions — Exceptions in PHP — throw, try, catch and finally, custom exception classes and built-in errors.

Thanks for reading!

Donate to the site — we work hard for you.