PHP Syntax OOP Exceptions Catch Multiple Exceptions

 

- Info:

- This tutorial shows how to react differently depending on which subclass of base Exception class was thrown.

- This is done by defining separate catch block for each Exception sublcass.

- If MyException is thrown it can be caught by catch block which accepts MyException or any of its superclasses.

- PHP will execute code from first catch block which matches the above criteria.

- That's why more specific classes (subclasses) are listed first and more general ones (superclassses) below them.

 

- Example:

- If in this example catch block that accepts Exception was given before the one accepting MyException catch block

which accepts MyException would never be executed since Exception would be caught by the first more general block.

- Creat PHP Console Application Test.php.

 

Test.php

<?php

class MyException extends Exception { }

try {

throw new MyException();

}

catch (MyException $e) {

echo 'Caught MyException';

}

catch (Exception $e) {

echo 'Caught general Exception';

}

?>