PHP Exceptions Tutorial

11/22/2025

PHP exceptions tutorial with try-catch examples

Go Back

PHP Exceptions Tutorial: A Complete Beginner-Friendly Guide

Exceptions in PHP allow you to handle errors in a clean, controlled, and professional way. Instead of your application crashing, exceptions let you catch problems and respond gracefully.

In this tutorial, you'll learn:

  • What exceptions are

  • How to throw and catch exceptions

  • Built-in exception classes

  • Custom exceptions

  • Exception chaining

  • Try-catch-finally structure

  • Real-world examples


PHP exceptions tutorial with try-catch examples

🔹 What Is an Exception?

An exception is an error event that stops normal program execution. You can handle these events using try, catch, and throw.

Why use exceptions?

  • Clean and readable error handling

  • Prevents script from crashing

  • Allows custom error messages

  • Works well in large applications

  • Mandatory in modern PHP frameworks (Laravel, Symfony)


🔸 Basic Exception Example

<?php
try {
    throw new Exception("Something went wrong!");
} catch (Exception $e) {
    echo "Caught Exception: " . $e->getMessage();
}
?>

Output:

Caught Exception: Something went wrong!

🔸 Throwing Exceptions

Use throw to manually raise an exception.

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

🔸 Catching Exceptions

Wrap risky code inside a try block.

try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo $e->getMessage();
}

🔸 Using Multiple Catch Blocks

Different exceptions can be handled separately.

try {
    // risky code
} catch (PDOException $e) {
    echo "Database Error: " . $e->getMessage();
} catch (Exception $e) {
    echo "General Error: " . $e->getMessage();
}

🔸 The finally Block

finally always executes—whether exception occurs or not.

try {
    echo "Trying...";
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    echo " Always executed.";
}

Custom Exception Class

You can create your own exception types.

class AgeException extends Exception {}

function checkAge($age) {
    if ($age < 18) {
        throw new AgeException("Age must be 18+.");
    }
    return "Access granted";
}

try {
    echo checkAge(16);
} catch (AgeException $e) {
    echo "Custom Error: " . $e->getMessage();
}

Exception Chaining

Pass the previous exception to preserve details.

try {
    throw new Exception("Low-level error");
} catch (Exception $e) {
    throw new Exception("High-level error", 0, $e);
}

You can inspect the entire chain using:

$e->getPrevious();

Converting PHP Errors to Exceptions

Use ErrorException to convert warnings/notices into exceptions.

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

Real-World Example: Database Connection

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

Real-World Example: File Handling

function readFileSafe($file) {
    if (!file_exists($file)) {
        throw new Exception("File not found: $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) {
    echo "Error: " . $e->getMessage();
}

🛡 Best Practices for Exceptions

  • Throw meaningful messages

  • Use custom exception classes in large applications

  • Convert PHP errors to exceptions for consistent handling

  • Never expose technical messages to end-users

  • Log exception details

  • Use finally to release resources (DB, file handles)


Summary

You learned:

  • What exceptions are in PHP

  • How to use try, catch, and finally

  • How to throw exceptions

  • Create custom exception types

  • Convert PHP warnings to exceptions

  • Real-world DB and file examples

Exceptions make PHP applications safe, robust, and professional.