How to Throw a Custom Exception in Case of No Match When Using PHP match Expression?

When a PHP match expression has no default pattern defined, it throws an UnhandledMatchError. Consider, for example, the following:

// PHP 8+
$status = 600;

echo match ($status) {
    200 => 'ok',
    301, 302, 307, 308 => 'redirect',
    400, 401 => 'bad request',
    404 => 'not found',
    500 => 'server error',
};

// Fatal error: Uncaught UnhandledMatchError

To throw a custom exception instead, you can do either of the following:

Using default

Starting with of PHP 8, the throw keyword is an expression (as opposed to a statement, as in earlier versions of PHP, where it required to be on its own line). Therefore, you can simply throw the custom exception in the default pattern of the match expression, for example, like so:

// PHP 8+
$status = 600;

echo match ($status) {
    200 => 'ok',
    301, 302, 307, 308 => 'redirect',
    400, 401 => 'bad request',
    404 => 'not found',
    500 => 'server error',
    default => throw new InvalidStatusCodeException($status),
};

// Fatal error: Uncaught InvalidStatusCodeException

Using try/catch

You can simply do the following:

  1. Wrap the match expression in a try/catch block;
  2. Catch the UnhandledMatchError error, and;
  3. Throw the custom exception in the catch block.

For example:

// PHP 8+
$status = 600;

try {
    echo match ($status) {
        200 => 'ok',
        301, 302, 307, 308 => 'redirect',
        400, 401 => 'bad request',
        404 => 'not found',
        500 => 'server error',
    };
} catch (UnhandledMatchError $e) {
    throw new InvalidStatusCodeException($status);
}

// Fatal error: Uncaught InvalidStatusCodeException

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.