The goal of this tutorial is to provide an understanding of Error Handling and Exception Management in PHP. By the end of this tutorial, you'll have the knowledge to handle various types of errors and exceptions in your PHP applications.
A basic understanding of PHP syntax and functions.
In PHP, there are two types of errors: Fatal errors and Non-fatal errors. Fatal errors stop the execution of the script, while Non-fatal errors allow the script to continue.
To handle errors, PHP provides several functions such as error_reporting()
, set_error_handler()
, and trigger_error()
.
This function sets the level of error reporting on your script. You can set it to report all errors or specific types of errors.
error_reporting(E_ALL); // Report all errors
This function sets a user-defined function to handle errors.
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
set_error_handler("customError");
This function triggers an error.
trigger_error("A custom error has been triggered.");
Exceptions are used to change the normal flow of a script if a specified error occurs. Exceptions are thrown and then caught to be handled.
try
is a block of code that lets you test a block of code for errors.
throw
is how you trigger an exception.
catch
is a block of code that will be executed if an exception is thrown in the try block.
try {
throw new Exception("An error occurred");
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
Handling a division by zero error.
// Set custom error handler
set_error_handler("customError");
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
$a = 10;
$b = 0;
if($b == 0){
trigger_error("Cannot divide by zero.");
}
else{
echo $a/$b;
}
In this example, a custom error handler is set. If we try to divide by zero, an error is triggered.
Handling an exception when a value is not numeric.
function checkNum($number) {
if(!is_numeric($number)) {
throw new Exception("Value must be numeric");
}
return true;
}
try {
checkNum('abc');
echo 'If you see this, the number is numeric';
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
In this example, an exception is thrown when the function checkNum
encounters a non-numeric value. The catch
block then handles this exception.
In this tutorial, we learned about the different types of errors in PHP and how to handle them. We also learned about exceptions and how to throw and catch them.
To further your knowledge, you can explore more about:
- Different types of exceptions in PHP
- How to create custom exceptions
Write a script that triggers an error when a string is passed instead of a number.
Write a script that throws an exception when a file does not exist.
Create a custom exception and write a script that throws and catches this exception.
Remember to use the functions and techniques we've covered in this tutorial. Happy coding!