Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Using throw as an expression in PHP 8

Up until now, when you want to throw exceptions from your code, you would use the throw keyword to throw the exception which can be caught by the catch block like so.

function test() 
{
    try {
        throw new Exception('foo');
    } catch (Exception $e) {
        return 'catch';
    } finally {
        return 'finally';
    }
}

echo test();

One thing to notice here is, in the version before PHP 8, the throw keyword was a statement. And so, it could be only used in the “block” context and not in places where only expressions are allowed, such as arrow functions, the coalesce operator, and the ternary/elvis operator.

But PHP 8 attempts to solve this.

The throw keyword as an expression

In PHP 8, the throw keyword now acts as an expression. As a result of this, you can now use them in the places I mentioned above.

Usage in arrow functions

So, if you want to use it in an arrow function, you can do it like so.

$callable = fn() => throw new Exception();

Usage in null coalescing operator

Or you can use it in conjunction with the null coalescing assignment operator like so.

$value = fn() => $nullableValue ?? throw new Exception();

Usage in ternary operation

Or in a ternary operation like so.

$value = !empty($array)
    ? reset($array)
    : throw new InvalidArgumentException();

Usage in conditionals

You can even use it in conditionals intuitively like so.

if ($condition || throw new Exception('Something went wrong!')) {
    // do your thing if the condition met
    // else throw an exception
}

This is equivalent to the following code in versions before PHP 8.

if ($condition) {
    // do your thing if the condition met
} else {
    // else throw an exception
    throw new Exception('Something went wrong!');
}
Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?