PHP Error Handling

11/22/2025

PHP error handling with try-catch and logging examples

Go Back

PHP Error Handling: A Complete Beginner-Friendly Guide

Errors are a natural part of developing applications in PHP, and handling them properly is essential for building reliable and secure systems. Instead of letting errors crash your application or display confusing messages, effective error handling allows developers to manage issues in a controlled and professional way.

Proper error handling helps you debug issues faster, ensuring that problems are identified and fixed quickly during development. It also plays a crucial role in protecting sensitive information, preventing internal system details from being exposed to users. Additionally, it enables you to display user-friendly messages, improving the overall user experience, while also allowing developers to log errors for future analysis and troubleshooting.

Errors are a natural part of developing PHP applications. Proper error handling helps you:

  • Debug issues faster

  • Prevent exposing sensitive information

  • Provide user‑friendly messages

  • Log problems for developers

This tutorial explains all essential PHP error handling techniques with examples.


PHP error handling with try-catch and logging examples

Types of Errors in PHP

Common PHP error types include:

  • Parse Error – Syntax issues (missing semicolon, bracket)

  • Fatal Error – Script stops (undefined class/function)

  • Warning – Non‑fatal problems; script continues

  • Notice – Minor issues (undefined variable)

  • Exception – Errors thrown using throw and handled by try...catch


Controlling Error Reporting

Use error_reporting() to show specific types of errors.

<?php
// Show all errors
error_reporting(E_ALL);

// Show warnings & errors only
error_reporting(E_ERROR | E_WARNING);
?>

Display errors (development)

ini_set('display_errors', 1);

Hide errors (production)

ini_set('display_errors', 0);
ini_set('log_errors', 1);

Example: Enable Error Display (Useful for Localhost)

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo $name; // Notice: undefined variable
?>

Handling Errors Using Try–Catch (Exceptions)

Exceptions allow graceful, controlled error handling.

Example:

<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Cannot divide by zero");
    }
    return $a / $b;
}

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

Handling Database Errors (PDOException)

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Database Error: " . $e->getMessage();
}
?>

Custom Error Handler Using set_error_handler()

Create your own function to process PHP errors.

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    $msg = "Error [$errno]: $errstr in $errfile on line $errline";
    error_log($msg);
    echo "Something went wrong. Please try again later.";
    return true; // Prevent default handler
}

set_error_handler("myErrorHandler");

echo $undefinedVar; // Triggers custom handler
?>

Converting Errors to Exceptions

<?php
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try {
    echo $undefinedVar;
} catch (ErrorException $e) {
    echo "Caught exception: " . $e->getMessage();
}
?>

 Logging Errors Manually

<?php
error_log("Custom log entry", 3, __DIR__ . "/app.log");
?>

Useful for debugging API failures, DB errors, etc.


Example: Safe File Read with Error Handling

<?php
function readFileSafe($file) {
    if (!file_exists($file)) {
        throw new Exception("File missing: $file");
    }

    $content = @file_get_contents($file);

    if ($content === false) {
        throw new Exception("Unable to read file: $file");
    }

    return $content;
}

try {
    echo readFileSafe("data.txt");
} catch (Exception $e) {
    error_log($e->getMessage());
    echo "Unable to load file.";
}
?>

Best Practices for PHP Error Handling

  • Show all errors in development; hide them in production

  • Log errors instead of showing them to users

  • Avoid exposing file paths, SQL queries, or stack traces

  • Use exceptions for DB queries, APIs, and risky operations

  • Always sanitize user input before using it

  • Convert PHP errors to exceptions for uniform handling


Summary

You learned:

  • Types of PHP errors

  • Error reporting and configuration

  • Try–catch blocks and exception handling

  • Custom error handlers

  • Safe file/database handling practices

Proper error handling improves security, performance, and user experience.