agyanadda@gmail.com

PHP Exceptions and Error Handling

OOP and Advanced PHP 1 min read Updated Dec 1, 2026 Topic 33 of 36

try / catch / finally

try {
    $result = divide(10, 0);
} catch (DivisionByZeroError $e) {
    echo 'Cannot divide by zero';
} finally {
    // always runs: close files, release locks
}

throw your own

if ($age < 18) {
    throw new InvalidArgumentException('Must be 18 or older');
}

Custom exceptions

class PaymentFailedException extends Exception {}

Catch specific types first, general Exception (or Throwable) last. Catch several at once: catch (TypeError | ValueError $e).

Useful methods

$e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine()

Development vs live server

Development Live server
display_errors = On display_errors = Off
error_reporting(E_ALL) log_errors = On

On a live site, log errors with error_log() and show visitors a friendly message — error details can reveal file paths and passwords.

Example

Example — Custom exception for wallet payments PHP
<?php
class InsufficientBalanceException extends Exception
{
    public function __construct(public readonly float $shortBy)
    {
        parent::__construct('Insufficient balance. Short by ₹' . number_format($shortBy, 2));
    }
}

function payFromWallet(float $balance, float $amount): float
{
    if ($amount <= 0) {
        throw new InvalidArgumentException('Amount must be positive.');
    }
    if ($amount > $balance) {
        throw new InsufficientBalanceException($amount - $balance);
    }
    return $balance - $amount;
}

$tests = [[1000, 300], [1000, 1500], [1000, -5]];

foreach ($tests as [$balance, $amount]) {
    try {
        $left = payFromWallet($balance, $amount);
        echo "Paid ₹$amount. Balance left: ₹$left<br>";
    } catch (InsufficientBalanceException $e) {
        echo $e->getMessage() . ' – please add money.<br>';
    } catch (InvalidArgumentException $e) {
        echo 'Invalid input: ' . $e->getMessage() . '<br>';
    } finally {
        echo '<small>Transaction checked.</small><br>';
    }
}

Output: Paid ₹300. Balance left: ₹700 / Insufficient balance. Short by ₹500.00 – please add money. / Invalid input: Amount must be positive. — each followed by "Transaction checked."

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which block always runs, whether an exception happened or not?

Exercise 2 True / False

display_errors should be On for a live website.

Exercise 3 Fill in the Blank

A custom exception class usually ___ Exception.

Frequently Asked Questions

Both implement Throwable. Exceptions are for expected problems you throw yourself; Errors (TypeError, DivisionByZeroError) come from PHP itself. catch (Throwable $e) catches both.