Example of a Notice:
<?php echo $undefined_variable; // Notice: Undefined variable ?>
Example of a Warning:
<?php
include('nonexistent_file.php'); // Warning: file not found
echo "Script continues...";
?>
Displaying Errors
During development, it’s helpful to display errors.
<?php
ini_set('display_errors', 1); // Turn on error display
error_reporting(E_ALL); // Show all errors and warnings
?>
Best practice:
ini_set('display_errors', 0);
Custom Error Handling Using set_error_handler()
PHP allows you to define a custom function to handle errors:
<?php
// Custom error function
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Error:</b> [$errno] $errstr - in $errfile on line $errline<br>";
}
// Set custom error handler
set_error_handler("myErrorHandler");
// Trigger an error
echo $undefined_variable; // Will call myErrorHandler
?>
$errno → Error number$errstr → Error message$errfile → File where error occurred$errline → Line number of errorHandling Fatal Errors Using register_shutdown_function()
Fatal errors stop script execution. You can detect them before the script ends:
<?php
function shutdownHandler() {
$error = error_get_last();
if ($error) {
echo "<b>Fatal Error:</b> {$error['message']} in {$error['file']} on line {$error['line']}";
}
}
register_shutdown_function('shutdownHandler');
// Trigger a fatal error
nonexistentFunction(); // Fatal error: function doesn't exist
?>
Try-Catch Exception Handling
PHP supports exceptions, which is a modern way to handle errors. This is preferred for critical operations, such as database access.
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=php_crud_demo", "root", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Trigger an exception
$conn->query("SELECT * FROM nonexistent_table");
} catch (PDOException $e) {
echo "Database Error: " . $e->getMessage();
} finally {
echo "<br>Execution finished.";
}
?>
Notes:
try block → Code that might throw an errorcatch block → Code to handle the errorfinally block → Runs no matter whatLogging Errors to a File
Instead of displaying errors to the user, you can log them to a file:
<?php
ini_set("log_errors", 1);
ini_set("error_log", "php_errors.log");
// Trigger an error
echo $undefined_variable;
?>
php_errors.log file for errors.Best Practices for Error Handling
✅ What this demo does:
set_error_handlertry-catch<?php
// Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "<b>Error:</b> [$errno] $errstr - in $errfile on line $errline<br>";
}
set_error_handler("myErrorHandler");
// Try-Catch Exception Handling
try {
$num = 10;
$den = 0;
if ($den == 0) {
throw new Exception("Division by zero not allowed!");
}
echo $num / $den;
} catch (Exception $e) {
echo "Caught Exception: " . $e->getMessage();
}
// Trigger a notice
echo $undefined_variable;
// Trigger a warning
include('nonexistent_file.php');
?>