Handling
Multiple Exception Types with one catch
Statement
Before PHP 7.1, you had to duplicate code that handles multiple exception types:
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:
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.