Handling multiple exceptions in PHP 7.1

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.

<?php
 
class MyFooException extends Exception {
    public function __construct($message = null, $code = 0) {
       echo $message;
    }
}
 
class MyBarException extends Exception {
    public function __construct($message = null, $code = 0) {
        echo $message;
    }
}
 
class MyBazException extends Exception {
    public function __construct($message = null, $code = 0) {
        echo $message;
    }
}
 
try {
    $error = "Baz Exception thrown.";
    throw new MyBazException($error);
}
catch(MyFooException $e) {
    echo "Caught a 'Foo' Exception";
    // Do something here
}
catch(MyBarException $e) {
    echo "Caught a 'Bar' Exception";
    // Do something here
}
catch(MyBazException $e) {
    echo "Caught a 'Baz' Exception";
    // Do something here
}

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.

try {
    $error = "Foo / Bar / Baz Exception";
    throw new MyBazException($error);
}
catch(MyFooException | MyBarException | MyBazException $e) {
    // Do something here
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>