Throw expressions and non-capturing catches

suggest change

PHP 8.0 made several small changes to how errors are raised and caught:

Later releases built on this. PHP 8.3 gave the date extension its own exception classes, such as DateMalformedStringException, and PHP 8.5 added get_error_handler() and get_exception_handler() and stack traces for fatal errors.

All examples were run with PHP 8.5. In the outputs, file paths are replaced with ....

For the basics of try / catch see Exception and Error handling. Defining your own exception classes is covered in Custom errors, and finally in try, finally, and cleanup.

throw is an expression (PHP 8.0)

Before PHP 8.0, throw was a statement, like echo or return. You could only use it on its own line, so a "get this value or fail" check took several lines:

$host = $env['DB_HOST'] ?? null;
if ($host === null) {
    throw new RuntimeException('missing config key: DB_HOST');
}

Now throw can appear wherever an expression is allowed. It never produces a value, because control leaves the expression the moment it runs. That makes it a natural right-hand side for the operators that pick between two values.

With the null coalescing operator ??

$a ?? throw ... returns $a if it is set and not null, and throws otherwise:

<?php
function config(array $env, string $key): string
{
    return $env[$key] ?? throw new RuntimeException("missing config key: $key");
}

$env = ['DB_HOST' => 'localhost'];
echo config($env, 'DB_HOST'), "\n";

try {
    echo config($env, 'DB_PASS'), "\n";
} catch (RuntimeException $e) {
    echo $e->getMessage(), "\n";
}

Output:

localhost
missing config key: DB_PASS

This is the most common use. It also works inside a function call, so a required argument can be checked where it is passed:

<?php
function load(int $id): string
{
    return "user $id";
}

$userId = $_GET['id'] ?? null;
try {
    echo load($userId ?? throw new InvalidArgumentException('id is required')), "\n";
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

Output:

id is required

The null coalescing assignment operator works too: $cache['x'] ??= throw new LogicException('x must be preloaded'); throws if $cache['x'] is not set.

With ?: and the ternary operator

The short ternary ?: throws when the left side is falsy. Use it when 0, '' or false mean failure:

<?php
function port(string $s): int
{
    $n = (int) $s;
    return $n ?: throw new InvalidArgumentException("bad port: '$s'");
}

echo port('5432'), "\n";
try {
    port('abc');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

Output:

5432
bad port: 'abc'

The full ternary is useful when the condition isn't about the value itself. Here it validates a property while assigning it:

<?php
final class Money
{
    public readonly int $cents;

    public function __construct(int $cents, public readonly string $currency)
    {
        $this->cents = $cents >= 0
            ? $cents
            : throw new DomainException("amount can't be negative: $cents");
        strlen($currency) === 3 || throw new DomainException("bad currency: $currency");
    }
}

echo (new Money(1999, 'EUR'))->cents, "\n";
foreach ([[-5, 'EUR'], [100, 'EURO']] as [$c, $cur]) {
    try {
        new Money($c, $cur);
    } catch (DomainException $e) {
        echo $e->getMessage(), "\n";
    }
}

Output:

1999
amount can't be negative: -5
bad currency: EURO

The last line of the constructor shows another form: condition || throw ... (or condition or throw ...) throws when the condition is false. It reads like Perl's open(...) or die, and the familiar PHP idiom works the same way:

$fh = @fopen($path, 'r') or throw new RuntimeException("cannot open $path");

Use it sparingly. An if statement is usually easier to read than a boolean expression whose result is thrown away.

In arrow functions

An arrow function body must be a single expression. Before 8.0 an arrow function couldn't throw at all. Now it can, which is handy for stubs and for callback tables where some entries aren't supported:

<?php
$notImplemented = fn() => throw new LogicException('not implemented');

try {
    $notImplemented();
} catch (LogicException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

$parsers = [
    'json' => fn(string $s) => json_decode($s, true, flags: JSON_THROW_ON_ERROR),
    'xml'  => fn(string $s) => throw new LogicException('xml is not supported yet'),
];

var_dump($parsers['json']('{"a":1}'));
try {
    $parsers['xml']('<a/>');
} catch (LogicException $e) {
    echo $e->getMessage(), "\n";
}

Output:

LogicException: not implemented
array(1) {
  ["a"]=>
  int(1)
}
xml is not supported yet

In match arms

match throws UnhandledMatchError if no arm matches. That error has a generic message. A default arm with throw lets you choose the exception class and the message:

<?php
enum Method { case Get; case Post; case Delete; }

function parseMethod(string $m): Method
{
    return match (strtoupper($m)) {
        'GET' => Method::Get,
        'POST' => Method::Post,
        'DELETE' => Method::Delete,
        default => throw new InvalidArgumentException("unsupported method: $m"),
    };
}

echo parseMethod('post')->name, "\n";
try {
    parseMethod('PATCH');
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

Output:

Post
unsupported method: PATCH

Precedence: throw takes everything to its right

throw has the lowest precedence of all operators. Everything after it is part of the thrown expression. $a ?? throw new E() works because ?? binds tighter, but adding anything after the new changes the meaning:

<?php
try {
    $v = null;
    $r = $v ?? throw new Exception('a') . 'b';
} catch (Exception $e) {
    var_dump($e->getMessage());
}

Output:

Fatal error: Uncaught Error: Can only throw objects in ...:4
Stack trace:
#0 {main}
  thrown in ... on line 4

PHP parsed this as throw (new Exception('a') . 'b'). The exception was converted to a string and concatenated, and throwing a string is an Error. Keep the thrown expression simple, or put the message together before the new.

Where throw still can't go

throw is not allowed in constant expressions: parameter defaults, property defaults, class constants and attribute arguments.

<?php
function f($x = throw new Exception('x')) {}

Output:

Fatal error: Constant expression contains invalid operations in ... on line 2
Stack trace:
#0 {main}

Catching without a variable (PHP 8.0)

Sometimes the type of the exception is all you need to know. Before PHP 8.0 you still had to name a variable, and static analysers and IDEs then warned about the unused $e. Now the variable is optional:

<?php
function parseDate(string $s): ?DateTimeImmutable
{
    try {
        return new DateTimeImmutable($s);
    } catch (DateMalformedStringException) {
        return null;
    }
}

var_dump(parseDate('2026-10-18')?->format('D, d M Y'));
var_dump(parseDate('yesterday-ish'));

Output:

string(16) "Sun, 18 Oct 2026"
NULL

It works with multi-catch as well. Here an invalid page size, either the wrong type or a value out of range, means "no pagination":

<?php
function pages(array $items, mixed $perPage): ?array
{
    try {
        return array_chunk($items, $perPage);
    } catch (TypeError | ValueError) {
        return null;
    }
}

$items = range(1, 5);
echo json_encode(pages($items, 2)), "\n";
echo json_encode(pages($items, '2')), "\n";
echo json_encode(pages($items, 'two')), "\n";
echo json_encode(pages($items, 0)), "\n";

Output:

[[1,2],[3,4],[5]]
[[1,2],[3,4],[5]]
null
null

Leaving out the variable says to the reader "the exception is expected here and its details don't matter". When you need the details, keep the variable. That includes logging, wrapping with previous:, or rethrowing. PHP has no bare throw; to rethrow the current exception, so rethrowing always needs a variable:

<?php
function readJsonFile(string $path): array
{
    $text = @file_get_contents($path);
    if ($text === false) {
        return [];                         // missing file: use defaults
    }
    try {
        return json_decode($text, true, flags: JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        throw new RuntimeException("invalid JSON in $path", previous: $e);
    }
}

Be careful with broad types. catch (Throwable) with no variable and no logging hides every bug in the try block, including typos that throw Error. Catch the narrowest class that describes the expected failure.

Internal functions throw TypeError and ValueError (PHP 8.0)

In PHP 7, passing a wrong argument to a built-in function usually produced a warning and a return value of null or false. strlen([]) printed Warning: strlen() expects parameter 1 to be string, array given and returned null. The script kept running with a bad value.

Since PHP 8.0, built-in functions behave like user functions with typed parameters:

Arithmetic and other operators also throw TypeError on unsupported operand types, and integer division by zero throws DivisionByZeroError:

<?php
$tests = [
    fn() => strlen([]),
    fn() => str_repeat('x', -1),
    fn() => array_chunk([1, 2, 3], 0),
    fn() => array_combine(['a', 'b'], [1]),
    fn() => range(1, 2, 0),
    fn() => 'abc' * 2,
    fn() => [] + 1,
    fn() => intdiv(1, 0),
    fn() => 1 % 0,
];

foreach ($tests as $t) {
    try {
        $t();
        echo "no exception\n";
    } catch (Throwable $e) {
        echo get_class($e), ': ', $e->getMessage(), "\n";
    }
}

Output:

TypeError: strlen(): Argument #1 ($string) must be of type string, array given
ValueError: str_repeat(): Argument #2 ($times) must be greater than or equal to 0
ValueError: array_chunk(): Argument #2 ($length) must be greater than 0
ValueError: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements
ValueError: range(): Argument #3 ($step) cannot be 0
TypeError: Unsupported operand types: string * int
TypeError: Unsupported operand types: array + int
DivisionByZeroError: Division by zero
DivisionByZeroError: Modulo by zero

The messages are consistent: function name, argument number and parameter name, and what was expected. They all extend Error, not Exception, because they signal a bug in the calling code. Normally you fix the call instead of catching them. Catch them only at a boundary where the input comes from outside, as in the pages() example above.

A few things did not change:

Date exceptions (PHP 8.3)

Before PHP 8.3 the date extension threw a plain Exception from constructors and returned false with a warning from methods such as modify(). To catch only bad dates, you had to catch Exception and hope nothing else threw one. PHP 8.3 added a hierarchy:

Exception
└── DateException
    ├── DateMalformedStringException          bad date/time string
    ├── DateMalformedIntervalStringException  bad DateInterval spec
    ├── DateMalformedPeriodStringException    bad ISO 8601 period
    ├── DateInvalidTimeZoneException          unknown time zone
    └── DateInvalidOperationException         sub() with a special relative interval
Error
└── DateError
    ├── DateObjectError                       object not initialized properly
    └── DateRangeError                        timestamp out of range (32-bit platforms)

The Exception branch is for bad input. The Error branch is for bugs, like other Error subclasses.

<?php
$inputs = ['2026-10-18', 'next friday', 'not a date', '2026-02-30', '2026-13-01'];
foreach ($inputs as $s) {
    try {
        $d = new DateTimeImmutable($s);
        echo str_pad($s, 12), ' -> ', $d->format('Y-m-d'), "\n";
    } catch (DateMalformedStringException $e) {
        echo str_pad($s, 12), ' -> ', $e->getMessage(), "\n";
    }
}

Output:

2026-10-18   -> 2026-10-18
next friday  -> 2026-10-23
not a date   -> Failed to parse time string (not a date) at position 0 (n): The timezone could not be found in the database
2026-02-30   -> 2026-03-02
2026-13-01   -> Failed to parse time string (2026-13-01) at position 6 (3): Unexpected character

Note that 2026-02-30 is not an error. The parser accepts it and rolls over to March 2. If you need strict validation, use DateTimeImmutable::createFromFormat() and check DateTimeImmutable::getLastErrors().

The other classes in action:

<?php
$d = new DateTimeImmutable('2026-10-18');

try {
    $next = $d->modify('+1 fortnight-ish');
} catch (DateMalformedStringException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    new DateInterval('P1Q');
} catch (DateMalformedIntervalStringException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    new DateTimeZone('Mars/Olympus_Mons');
} catch (DateInvalidTimeZoneException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

try {
    $prev = $d->sub(DateInterval::createFromDateString('next weekday'));
} catch (DateInvalidOperationException $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

Output:

DateMalformedStringException: DateTimeImmutable::modify(): Failed to parse time string (+1 fortnight-ish) at position 12 (-): Unexpected character
DateMalformedIntervalStringException: Unknown or bad format (P1Q)
DateInvalidTimeZoneException: DateTimeZone::__construct(): Unknown or bad timezone (Mars/Olympus_Mons)
DateInvalidOperationException: DateTimeImmutable::sub(): Only non-special relative time specifications are supported for subtraction

modify() throwing is a behaviour change. Code that checked if ($d->modify(...) === false) must catch DateMalformedStringException on 8.3 and later. Since all of these extend DateException, catch (DateException) handles any bad date input in one place.

The procedural functions and the createFromFormat() factories did not change. They still return false:

<?php
var_dump(date_create('not a date'));
var_dump(DateTimeImmutable::createFromFormat('Y-m-d', 'nope'));

Output:

bool(false)
bool(false)

Error and exception handlers (PHP 8.5)

set_error_handler() and set_exception_handler() return the previous handler, but until PHP 8.5 there was no way to just read the current one. The usual workaround was to install a dummy handler and immediately restore the old one:

<?php
$h = fn() => true;
set_error_handler($h);

// before PHP 8.5: swap in a dummy handler, then put the old one back
$current = set_error_handler(null);
restore_error_handler();
var_dump($current === $h);

// PHP 8.5
var_dump(get_error_handler() === $h);

Output:

bool(true)
bool(true)

get_error_handler() and get_exception_handler() return the current callable, or null if none is set. They help code that must leave handlers as it found them. Test frameworks use them to detect tests that leak a handler. The helper below turns warnings into ErrorException for one call, and the check at the end confirms it restored the previous handler:

<?php
function withErrorsAsExceptions(callable $fn): mixed
{
    set_error_handler(function (int $no, string $msg, string $file, int $line): never {
        throw new ErrorException($msg, 0, $no, $file, $line);
    });
    try {
        return $fn();
    } finally {
        restore_error_handler();
    }
}

$before = get_error_handler();
try {
    withErrorsAsExceptions(fn() => file_get_contents('missing.txt'));
} catch (ErrorException $e) {
    echo $e->getMessage(), "\n";
}
var_dump(get_error_handler() === $before);

Output:

file_get_contents(missing.txt): Failed to open stream: No such file or directory
bool(true)

They also make it easy to wrap an existing handler instead of replacing it:

<?php
set_exception_handler(function (Throwable $e) {
    echo "outer: ", $e->getMessage(), "\n";
});

$inner = get_exception_handler();
set_exception_handler(function (Throwable $e) use ($inner) {
    echo "logging ", get_class($e), "\n";
    $inner($e);
});

throw new RuntimeException('boom');

Output:

logging RuntimeException
outer: boom

PHP 8.5 also prints a stack trace for fatal errors that are not exceptions, such as exceeding memory_limit or max_execution_time, and adds a trace key to error_get_last(). This is controlled by the fatal_error_backtraces ini setting (on by default) and is covered in Stack traces.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents