Skip to content
AgileLogics
5 min read

Exceptions & Error Handling

Prerequisites: Enums

try/catch/finally handle recoverable failures — thrown as objects, exactly like Java and C#.

function divide(float $a, float $b): float
{
    if ($b === 0.0) {
        throw new InvalidArgumentException('Cannot divide by zero');
    }
    return $a / $b;
}

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

A custom exception extends Exception (or a more specific built-in subclass) for domain-specific errors:

class InsufficientFundsException extends RuntimeException {}

throw new InsufficientFundsException("Balance too low");

Common mistakes

  • Catching the generic Exception (or Throwable) everywhere "to be safe" — catch the specific type you actually expect and know how to handle.