Error handling using try catch block in PHP

Solution:

try..catch handles exceptions. None of the code you show will ever throw an exception. So the catch block will never be invoked. Errors are something else in PHP which are not exceptions. Errors can only be silenced (using @ or global error_reporting settings) or handled globally using a defined error handler.

try..catch simply isn’t applicable to your code, however much you want it to be.


Having said that, you can use a custom error handler to turn any error into an exception. That’s what the ErrorException class is for. See its example in the manual. That would enable you to use try..catch for everything. Arguably this isn’t a bad idea, since PHP’s split error/exception mechanism is weird.