How to Handle Errors in PHP: Simple Guide for Beginners
try-catch blocks for exceptions and setting error_reporting levels for warnings or notices. You can also create custom error handlers with set_error_handler() to control how errors are processed.Why This Happens
Errors in PHP happen when the code tries to do something wrong, like dividing by zero or using a variable that doesn't exist. Without handling, PHP shows error messages that can stop your program or confuse users.
<?php // Broken code: division by zero causes a warning $result = 10 / 0; echo "Result is $result"; ?>
The Fix
Use try-catch blocks to catch exceptions and handle them gracefully. For warnings like division by zero, you can check conditions before running code or set a custom error handler to manage errors without stopping the script.
<?php // Fixed code using try-catch for exceptions function divide($a, $b) { if ($b == 0) { throw new Exception("Cannot divide by zero."); } return $a / $b; } try { $result = divide(10, 0); echo "Result is $result"; } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>
Prevention
Always validate inputs before using them in calculations or functions. Use error_reporting(E_ALL) and ini_set('display_errors', 1) during development to see all errors. Create custom error handlers with set_error_handler() to log or display errors in a user-friendly way.
<?php // Example of setting error reporting and custom error handler error_reporting(E_ALL); ini_set('display_errors', 1); set_error_handler(function($errno, $errstr, $errfile, $errline) { echo "Custom error: [$errno] $errstr on line $errline in file $errfile\n"; }); // Trigger a warning echo $undefined_variable; ?>
Related Errors
Common related errors include Fatal errors when calling undefined functions, Parse errors from syntax mistakes, and Notice errors from using undefined variables. Use try-catch for exceptions and proper validation to avoid these.
| Error Type | Cause | Quick Fix |
|---|---|---|
| Fatal error | Calling undefined function | Check function names and include files |
| Parse error | Syntax mistake | Fix code syntax, missing semicolons or braces |
| Notice | Using undefined variable | Initialize variables before use |