PHP Errors
Explore how PHP handles errors and exceptions by learning to differentiate between warnings and exceptions, configure error reporting, and create custom error handlers for consistent error management. Understand best practices to escalate PHP errors as exceptions to improve debugging and ensure your scripts stop executing when critical issues arise.
We'll cover the following...
Using exceptions to stop the execution
As a programmer, you can use exceptions to stop the execution of a function or an entire script. Throwing an exception means there is a problem, and you can’t continue. Once you throw an exception, the remaining code in the function or script will no longer be executed:
Using PHP errors
Besides exceptions, PHP has another mechanism for dealing with problems: PHP errors.
PHP errors are used to indicate that something is wrong, but they don’t necessarily stop the execution of the script.
When you open a file using fopen() but the file doesn’t exist, you will get a PHP error of type “warning”.
But this doesn’t stop the execution of the script.
Let’s find out how that works by putting the following code in oops.php:
Note that the throw new RuntimeException(...) statement was commented out, so this script will no longer throw an exception.
Now start the PHP server in development mode (with only php.ini):
php -S 0.0.0.0:8000 -t public/ -c php.ini
You don’t have to worry about going anywhere as we have already set everything up for you on our platform. ...