PHP Errors

Let's learn about PHP errors and how to use them.

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:

Press + to interact
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:

Press + to interact
<?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. ... ...

Access this course and 1400+ top-rated courses and projects.