PHP Exceptions – Complete Guide

PHP Exceptions provide a structured way to handle errors using try, catch, and throw.
They prevent the script from crashing by catching and managing unexpected conditions.
You can create custom exception classes for application-specific errors.
The finally block allows you to run cleanup code regardless of exceptions.
PHP also supports global exception handling using set_exception_handler().

1. Basic Try-Catch Example


try {
    // Risky code
    throw new Exception("Something went wrong!");
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

File: exception_basic.php

2. Custom Exception Class


class MyException extends Exception {}

try {
    throw new MyException("Custom error occurred!");
} catch (MyException $e) {
    echo "Caught custom exception: " . $e->getMessage();
}

File: custom_exception.php

3. Multiple Catch Blocks


class AppException extends Exception {}
class DbException extends Exception {}

try {
    throw new DbException("Database failed!");
} catch (DbException $e) {
    echo "DB Error: " . $e->getMessage();
} catch (AppException $e) {
    echo "App Error: " . $e->getMessage();
}

File: multiple_catch.php

4. Finally Block


try {
    echo "Trying something risky...\n";
    throw new Exception("Oops!");
} catch (Exception $e) {
    echo "Caught: " . $e->getMessage() . "\n";
} finally {
    echo "Finally block always runs!";
}

File: finally_block.php

5. Set Custom Global Exception Handler


function myExceptionHandler($e) {
    echo "Custom Handler: " . $e->getMessage();
}

set_exception_handler("myExceptionHandler");

// Trigger global handler
throw new Exception("Unhandled exception!");

File: global_handler.php

6. Throwing Exception Based on Condition


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

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

File: conditional_exception.php

Summary Table

Concept PHP Code Keyword File Name
Basic Try-Catch try, catch exception_basic.php
Custom Exception Class class MyException custom_exception.php
Multiple Catches catch (Type $e) multiple_catch.php
Always run code finally finally_block.php
Global Handler set_exception_handler() global_handler.php
Throw on condition throw new Exception() conditional_exception.php