SyntaxStudy
Sign Up
PHP PHP Exception Handling Introduction
PHP Intermediate 4 min read

PHP Exception Handling Introduction

PHP Exceptions

Exceptions represent exceptional conditions that disrupt normal program flow. PHP uses try/catch/finally blocks to handle them gracefully.

Example
<?php
try {
    $result = divide(10, 0);
    echo $result;
} catch (DivisionByZeroError $e) {
    echo "Cannot divide by zero: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    echo "This always runs";
}

function divide(int $a, int $b): float {
    if ($b === 0) throw new DivisionByZeroError("Division by zero");
    return $a / $b;
}
Pro Tip

Catch the most specific exception types first — PHP matches the first catch block whose type fits the thrown exception.