Search⌘ K
AI Features

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.

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:

Javascript (babel-node)
throw new RuntimeException('Something went wrong');
echo 'This will never appear on the page';

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:

PHP
<?php
fopen(__DIR__ . '/this-file-does-not-exist', 'r');
echo 'PHP does not stop execution, even when it triggers an error';
//throw new RuntimeException('Something went wrong');

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. ...