SyntaxStudy
Sign Up
PHP Intermediate 4 min read

Throwing Exceptions

Throwing Exceptions

Use throw to raise an exception. PHP 8 allows throw as an expression, enabling it in arrow functions, ternaries, and null coalescing.

Example
<?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");
Pro Tip

PHP 8 throw expressions let you validate and throw inline — great for ??= and arrow functions.