Php Exception Handling

Home >> Blog >> Php Exception Handling

PHP's try and catch can be used to catch multiple exception types. In PHP Exception Handling, If the try block could cause one of several different exceptions they can each be handled separately with their own catch section.
Handling multiple exceptions:
It's very simple - there can be a catch block for each exception type that can be thrown:
//PHP Exception Handling try { // some code that might trigger a ABC/XYZ/PQR/Exception } catch(ABCException $e) { // we caught a ABC exception } catch(XYZException $e) { // we caught a XYZ exception } catch(PQRException $e) { // we caught a PQR exception } catch(Exception $e) { // we caught a normal exception // or an exception that wasn't handled by any of the above }
You may also like - Core PHP Interview Questions Answers
If an exception is thrown that is not handled by any of the other catch statements it will be handled by the catch(Exception $e) block. It does not necessarily have to be the last one.

Note that if each catch block has the same code to handle the exception than the result is code duplication.

Now, Exception Handling 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 = "ABC / XYZ / PQR Exception"; throw new XYZException($error); } catch(ABCException | XYZException | PQRException $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.
You may also like - MySQL Interview Questions