How to Handling multiple exceptions in PHP 7.1

5 (100%) 1 vote

BestASPNETHostingReview.com | Best and cheap PHP 7 Hosting. In this post I would like to show to how to handling multiple exceptions in PHP 7. Exception handling is one of the ways in which modern languages handle errors. PHP usually handles exception in a separate catch block for each different type of exception. Below is a example exception code that uses three custom exceptions ‘MyFooException’, ‘MyBarException’ and ‘MyBazException’ that is later handled in a ‘try’ block.

Note that if each catch block has the same code to handle the exception than the result is code duplication. Now in PHP 7.1 you can handle multiple types of exceptions in a single catch block by using a pipe ‘|’ character. The above code to handle the exception will now be changed as below; assuming that the code in the catch block will be the same to handle all three exception types.

This now prevents code duplication and any error from creeping in if one the catch block is handled differently than the other.

hflbnner