# Handling Multiple Exception Types with one `catch` Statement

> Section in “New and Extended Functionality › Error Handling” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/error-handling/handling-multiple-exception-types-with-one-catch-statement/>

Before PHP 7.1, you had to duplicate code that handles multiple exception types:

``` php
try {
    // ...
} catch (SomeDomainException $e) {
    $this->logger->log('Transaction failed: ' . $e->getMessage());
} catch (PersistenceException $e) {
    $this->logger->log('Transaction failed: ' . $e->getMessage());
} catch (Exception $e) {
    // do something else for other exception types
}
```

In the example above, the same code is used to handle the `SomeDomainException` and `PersistenceException` exception types. This code is duplicated in the two respective `catch` statements.

Starting with PHP 7.1 you can handle multiple exception types using a single catch statement:

``` php
try {
    // ...
} catch (SomeDomainException|PersistenceException $e) {
    $this->logger->log('Transaction failed: ' . $e->getMessage());
} catch (Exception $e) {
    // do something else for other exception types
}
```

In the example shown above, the code that handles the `SomeDomainException` and `PersistenceException` exception types is no longer duplicated.

While this syntactical addition may seem like a neat treat at first glance, any requirement to use it to avoid the duplication is a very likely sign for a so called leaky abstraction, making the calling code deal with implementation details of the collaborator.

---

Previous: [JSON_THROW_ON_ERROR](https://php7explained.com/new-and-extended-functionality/error-handling/json_throw_on_error/index.html.md) | Next: [Type System](https://php7explained.com/new-and-extended-functionality/type-system/index.html.md)
