Catch Multiple Exceptions Within A Single Catch Block in PHP

As of PHP 7.1, it is now possible to catch multiple exceptions within 1 catch block. This is super useful, as before you would have had to come up with a few work arounds to solve something like this in a similar fashion. For instance, you may have created a base class that multiple related classes extend from in order to catch those Exceptions within a single block.

Let’s look at an example of how this works.

First we’ll start by setting up our exceptions.

<?php

class InvalidFirstNameException extends Exception
{
}

class InvalidLastNameException extends Exception
{
}

Next, let’s setup our person class.

<?php

class Person
{
    private $firstName, $lastName;

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function setFirstName($firstName)
    {
        $this->checkAgainstInvalidFirstName($firstName);

        $this->firstName = $firstName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function setLastName($lastName)
    {
        $this->checkAgainstInvalidLastName($lastName);

        $this->lastName = $lastName;
    }

    private function checkAgainstInvalidFirstName($firstName)
    {
        if (!is_string($firstName)) {
            throw new InvalidFirstNameException('Invalid First Name. Must be a string.');
        }
    }

    private function checkAgainstInvalidLastName($lastName)
    {
        if (!is_string($lastName)) {
            throw new InvalidLastNameException('Invalid Last Name. Must be a string.');
        }
    }
}

You’ll see above that we have 2 functions that each throw a different exception depending on if the information passed is correctly formatted or not.

Now for the fun part. Let’s handle multiple exceptions.

<?php

try {
    $person = new Person;
    $person->setFirstName('Frank');
    $person->setLastName(12345);
} catch (InvalidFirstNameException | InvalidLastNameException $exception) {
    echo $exception->getMessage();
}

You can see above, that you simply just use a pipe character | to separate the exception names.