Skip to content

PHP 7.1 – Catching Multiple Exception Types

We general use PHP’s try..catch blocks to handle exceptions. If the try block could cause one of several different exceptions they can each be handled separately with their own catch section. As shown below

getMessage()}\n";
    } catch (ExceptBar $exception) {
        echo "Message: {$exception->getMessage()}\n";
    } catch (Exception $exception) {
        echo "Message: {$exception->getMessage()}\n";
    }
?>

If you observe the above example, we are handling the all the exceptions in the same way and we are duplicating the code of each catch statement.

PHP 7.1 introduces the possibility to catch multiple exception types in a single catch statement to avoid code duplication. Below is the example –

getMessage()}\n";
    }
?>
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments