How to Catch Multiple Exceptions in PHP?

Find out how you can handle multiple exceptions in PHP

In PHP 7.1+, you can catch multiple exceptions in the following way:

// PHP 7.1+
try {
    // ...
} catch (RuntimeException | InvalidArgumentException $e) {
    // ...
} catch (BadMethodCallException $e) {
    // ...
}

In the code above you can see that in the both, RuntimeException and InvalidArgumentException, have a common catch block and BadMethodCallException has a different catch block.

In versions prior to PHP 7.1, you can catch multiple exceptions in the following ways:

Creating Common Error Handlers

You could define functions/methods that handle common error code and call them on individually caught exceptions, for example, like so:

try {
    // ...
} catch (RuntimeException $e) {
    handler1();
} catch (InvalidArgumentException $e) {
    handler1();
} catch (BadMethodCallException $e) {
    // ...
}

Grouping Exceptions

You could group common exception classes and catch them collectively, for example, like so:

class HttpException extends RuntimeException {}
class RequestException extends HttpException {}
class ResponseException extends HttpException {}

try {
    // ...
} catch (HttpException $e) {
    // ...
} catch (BadMethodCallException $e) {
    // ...
}

Or, using an interface:

interface HttpExceptionInterface {}
class RequestException extends RuntimeException implements HttpExceptionInterface {}
class ResponseException extends RuntimeException implements HttpExceptionInterface {}

try {
    // ...
} catch (HttpExceptionInterface $e) {
    // ...
} catch (BadMethodCallException $e) {
    // ...
}

Using instanceof

You could catch all exceptions with "Exception" and then check which exception was thrown with instanceof, for example, like so:

try {
    // ...
} catch (Exception $e) {
    if ($e instanceof RuntimeException || $e instanceof InvalidArgumentException) {
        // ...
        return;
    } elseif ($e instanceof BadMethodCallException) {
        // ...
        return;
    }

    throw $e;
}

Using get_class()

You could catch all exceptions with "Exception" and then check which exception was thrown with get_class, for example, like so:

try {
    // ...
} catch (Exception $e) {
    switch (get_class($e)) {
        case RuntimeException::class:
        case InvalidArgumentException::class:
            // ...
            break;
        case BadMethodCallException::class:
            // ...
            break;
        default:
            throw $e;
    }
}

Hope you found this post useful. It was published . Please show your love and support by sharing this post.