Throwing Exceptions
Use throw to raise an exception. PHP 8 allows throw as an expression, enabling it in arrow functions, ternaries, and null coalescing.
Use throw to raise an exception. PHP 8 allows throw as an expression, enabling it in arrow functions, ternaries, and null coalescing.
<?php
// Traditional throw statement
function getUser(int $id): array {
$user = db_query("SELECT * FROM users WHERE id = ?", [$id]);
if (!$user) {
throw new RuntimeException("User {$id} not found");
}
return $user;
}
// PHP 8: throw as expression
$age = $_GET["age"] ?? throw new InvalidArgumentException("Age required");
$user = findUser($id) ?? throw new NotFoundException("User not found");
$value = $condition
? "valid value"
: throw new LogicException("Invalid condition");
PHP 8 throw expressions let you validate and throw inline — great for ??= and arrow functions.