0
0
PhpDebug / FixBeginner · 4 min read

How to Handle Errors in PHP: Simple Guide for Beginners

In PHP, you handle errors by using 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
<?php
// Broken code: division by zero causes a warning
$result = 10 / 0;
echo "Result is $result";
?>
Output
Warning: Division by zero in /path/to/script.php on line 3 Result is
🔧

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
<?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();
}
?>
Output
Error: Cannot divide by zero.
🛡️

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
<?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;
?>
Output
Custom error: [8] Undefined variable $undefined_variable on line 11 in file /path/to/script.php
⚠️

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 TypeCauseQuick Fix
Fatal errorCalling undefined functionCheck function names and include files
Parse errorSyntax mistakeFix code syntax, missing semicolons or braces
NoticeUsing undefined variableInitialize variables before use

Key Takeaways

Use try-catch blocks to handle exceptions and prevent script crashes.
Set error reporting to E_ALL and display errors during development.
Validate inputs to avoid runtime errors like division by zero.
Create custom error handlers with set_error_handler() for better control.
Understand common PHP error types to quickly fix issues.