Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

InvalidArgumentException

InvalidArgumentException is a LogicException that application code can throw when an argument has an inappropriate type.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

throw new InvalidArgumentException("string label required")

InvalidArgumentException is a LogicException that application code can throw when an argument has an inappropriate type. It does not automatically replace engine TypeError from a declared parameter type. In the example a mixed parameter validates its own contract and explicitly rejects numbers, while the typed function rejects the same number under strict_types.

declare(strict_types=1);
function label(mixed $x): string {
    if (!is_string($x)) { throw new InvalidArgumentException("string label required"); }
    return strtoupper($x);
}
function typed(string $x): string { return $x; }
echo label("ok"), PHP_EOL;
foreach ([fn() => label(3), fn() => typed(3)] as $call) {
    try { $call(); } catch (Throwable $e) { echo get_class($e), PHP_EOL; }
}
OK
InvalidArgumentException
TypeError

Examples

<?php
declare(strict_types=1);
function label(mixed $x): string {
    if (!is_string($x)) { throw new InvalidArgumentException("string label required"); }
    return strtoupper($x);
}
function typed(string $x): string { return $x; }
echo label("ok"), PHP_EOL;
foreach ([fn() => label(3), fn() => typed(3)] as $call) {
    try { $call(); } catch (Throwable $e) { echo get_class($e), PHP_EOL; }
}

Result

OK
InvalidArgumentException
TypeError

Sources