There is such code:

<?php class customException extends Exception{} $a; try{ if(!isset($a)){ $thrower = new customException("Variable not initialize"); throw $thrower; } echo $a."\n"; } catch(Exception $e){ echo $e->getMessage()."\n"; } var_dump($thrower instanceof Exception); ?> 

And it will work! Only I do not understand why? After all, we "threw" an exception to the customException class, why then is it compatible with the Exception class?

    1 answer 1

    This is due to the fact that all exceptions are inherited from the base class Exception . Therefore, specifying Exception in the catch you get the opportunity to intercept all its heirs.

    In PHP 7, common errors are also treated as exceptions and can be intercepted using try ... catch (not everything is true, division by zero, for example, made not intercepted). Errors are inherited from the new Error base class, therefore, when Exception and its heirs do not catch them.

    • that is, it is a linguistic convention that we can “catch” the parent and “throw out” the descendant? And then what is the difference between the Exception and Error classes, as far as I know there is the ErrorException class (but really it inherits from Exception) - MaximPro
    • @MaximPro For a long time in PHP errors, warnings and comments were issued to the standard error stream. Their display was regulated at the level of php.ini directives. With PHP 7, we decided to make errors as exceptions, but in order not to break backward compatibility, the error inheritance tree was made completely independent of the Exception tree, including ErrorException. This process is related to the fact that PHP was originally developed as a non-object-oriented language, and object-oriented features are still being incorporated into it. - cheops
    • I know that php was originally only a procedural programming language, respectively, there were no "features" oop. - MaximPro
    • @MaximPro, I just to the fact that these two types of exceptions decided to make independent. You can also make independent exceptions in your code if you catch descendants, and not the base class. - cheops
    • and I can also create my own class by implementing the Throwable ps interface. And how can you do it like you said? - MaximPro