3.5 Exception Handling
Exception handling is a core feature of almost any programming language. Exception handling is not only necessary to detect errors but also for flow control. PHP provides a powerful exception-handling model that can easily be used by programmers. To show you how exception handling can be done, we have included a simple example:
<?php $a = "a string"; if (sqrt($a)) { echo "Result: $b"; } else { echo "The operation cannot be performed"; } ?>
First, a string is defined. Then the script tries to compute the square root of the string, which is not possible. Therefore the condition evaluated by the if statement is not true and the else branch is entered.
If something happens that is not allowed in the script, it is necessary to quit the execution of a program. This can easily be done with the help of the die function:
<?php $a = 3; if ($a < 5) { echo '$a is lower than 5'; exit; } echo "This won't be executed"; ?>
As you can see, $a is lower than 5, so the if condition is true and the script quits:
$a is lower than 5
The output of the echo command at the end of the script won't be displayed any more.
exit is not the only function provided by PHP to exit a script. If a message has to be displayed before exiting a script, die can be used instead of exit.
<?php $a = 3; array_push($a, 4) or die ('$a is not an array'); echo "This won't be executed"; ?>
A PHP error message is displayed on the screen. In addition, the message that has been passed to die is displayed as well:
Warning: First argument to array_push() needs to be an array in /var/www/html/index.php on line 3 $a is not an array
For real-world applications the error message generated by PHP is not suitable because it makes the user think that an error in the application has occurred. To make sure that no error is displayed to PHP, you can use @ to suppress the error:
<?php $a = 3; @array_push($a, 4) or die ('$a is not an array'); echo "This won't be executed"; ?>
If you execute the script, you will see that no PHP error is displayed:
$a is not an array
As you can see, PHP provides a flexible exception-handling system that can easily be used to catch almost all errors occurring during the execution of a script.