📡 You're offline — showing cached content
New version available!
Quick Access
PHP Beginner

PHP Error Handling: try, catch, finally and Custom Exceptions

Learn try-catch-finally, multiple exception types, and custom Exception classes.

EzyCoders Admin May 23, 2026 2 min read 6 views
PHP Error Handling: try, catch, finally and Custom Exceptions
Share: Twitter LinkedIn WhatsApp

What is it?

Exception handling lets your application respond gracefully when things go wrong — database timeouts, missing files, invalid data — instead of crashing or showing raw errors to users.

Why does it matter?

Production applications fail in unexpected ways. Without error handling a database connection failure shows a cryptic error to the user. With it, you log the real error and show a friendly message.

Learn try-catch-finally, multiple exception types, and custom Exception classes.

Real-World Use Cases

  • 🗄️ Database connection failures - Wrap PDO connection in try-catch, log the real error, return 503 Service Unavailable to the user.
  • 📂 File operations - Catch exceptions when reading config files — fall back to default settings if the file is missing.
  • 🌐 API calls - Wrap cURL calls in try-catch, catch timeouts separately, and retry once before failing with a user message.
  • Form validation - Throw a ValidationException with an array of field errors and catch it at the controller level to redisplay the form.

try-catch-finally

<?php

try {
    $num = 10 / 0;

    echo $num;

} catch (DivisionByZeroError $e) {

    echo "Error: " . $e->getMessage();

} finally {

    echo "\nFinally block always runs";
}
?>

Catching Multiple Exception Types

<?php

try {

    $age = -5;

    if ($age < 0) {
        throw new InvalidArgumentException("Age cannot be negative");
    }

} catch (InvalidArgumentException | RuntimeException $e) {

    echo "Caught: " . $e->getMessage();
}
?>

Custom Exceptions

<?php

class AgeException extends Exception
{
}

function checkAge($age)
{
    if ($age < 18) {
        throw new AgeException("Age must be 18 or above");
    }

    return "Access granted";
}

try {

    echo checkAge(15);

} catch (AgeException $e) {

    echo "Custom Exception: " . $e->getMessage();
}
?>

Q: Should I show the exception message to the user?

Never show raw exception messages in production — they reveal file paths and database names. Log the full error server-side with error_log() and show a generic message to users.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment