PHP Throw Expression

Description

Since [PHP 8.0](PHP 8.0), throw can also be used as an expression[fn:throw].

Syntax

// This was previously not possible since arrow functions only accept a single expression while throw was a statement.
$callable = fn() => throw new Exception();

// value = $nullableValue ?? throw new InvalidArgumentException();

// value = $falsableValue ?: throw new InvalidArgumentException();

// value = !empty(array)
: throw new InvalidArgumentException();

condition && throw new Exception(); condition || throw new Exception();
condition or throw new Exception();

Footnotes

[fn:throw]https://wiki.php.net/rfc/throw\_expression