0Pricing
PHP Academy · Lesson

Try, Catch, and Finally

Handle runtime exceptions gracefully with try/catch/finally blocks.

Try, Catch, and Finally is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Exceptions vs Errors

PHP has two ways to signal problems:

  • Errors — traditional PHP notices/warnings/fatals (discussed previous lesson)
  • Exceptions — objects thrown when something exceptional happens; caught with try/catch

Exceptions are the modern, preferred approach for handling recoverable errors.

Throwing an Exception

Use throw to signal that something went wrong:

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

echo divide(10, 2);   // 5
// divide(10, 0);     // throws exception

try / catch Block

Wrap potentially throwing code in try and handle exceptions in catch:

<?php
try {
    $result = divide(10, 0);
    echo $result;
} catch (InvalidArgumentException $e) {
    echo 'Error: ' . $e->getMessage();
    echo ' in ' . $e->getFile() . ':' . $e->getLine();
}

Multiple catch Blocks

Catch different exception types in separate catch blocks:

<?php
try {
    $pdo = new PDO($dsn, $user, $pass);
    $result = performQuery($pdo);
} catch (PDOException $e) {
    error_log('DB error: ' . $e->getMessage());
    echo 'Database unavailable';
} catch (RuntimeException $e) {
    echo 'Runtime error: ' . $e->getMessage();
} catch (\Throwable $e) {
    echo 'Unexpected error: ' . $e->getMessage();
}

finally Block

finally runs regardless of whether an exception was thrown — perfect for cleanup:

<?php
$connection = null;
try {
    $connection = openDatabaseConnection();
    $data = fetchData($connection);
} catch (DatabaseException $e) {
    error_log($e->getMessage());
    echo 'DB error';
} finally {
    // Always runs — even if exception was thrown
    if ($connection) {
        closeConnection($connection);
    }
}

Exception Hierarchy

PHP's exception class hierarchy:

  • Throwable (interface)
  • ├─ Error — PHP engine errors (TypeError, ParseError…)
  • └─ Exception — application exceptions
  • ├─ RuntimeException
  • ├─ InvalidArgumentException
  • ├─ LogicException
  • └─ PDOException

Catching Throwable

Catch both Exceptions and PHP Errors with Throwable:

<?php
try {
    $result = someFunction();
} catch (\Exception $e) {
    echo 'Exception: ' . $e->getMessage();
} catch (\Error $e) {
    echo 'PHP Error: ' . $e->getMessage();
}

// Or catch both at once:
try {
    // ...
} catch (\Throwable $e) {
    echo get_class($e) . ': ' . $e->getMessage();
}

Union Catch (PHP 8)

PHP 8 allows catching multiple exception types in one catch block:

<?php
try {
    processRequest();
} catch (InvalidArgumentException | RuntimeException $e) {
    echo 'Handled: ' . $e->getMessage();
}

// Compare PHP 7 approach:
// catch (InvalidArgumentException $e) { ... }
// catch (RuntimeException $e) { ... }

Re-throwing Exceptions

Catch, log, and re-throw an exception to bubble it up the call stack:

<?php
function processOrder(int $id): void {
    try {
        $order = loadOrder($id);
        $order->process();
    } catch (PaymentException $e) {
        error_log('Payment failed for order ' . $id . ': ' . $e->getMessage());
        throw $e;  // re-throw after logging
    }
}

Exception Chaining

Pass the original exception as a 'previous' to preserve context:

<?php
try {
    $data = fetchFromAPI();
} catch (NetworkException $e) {
    throw new ServiceUnavailableException(
        'Cannot reach upstream service',
        0,
        $e  // $previous — preserves original cause
    );
}

// Retrieve original:
// $e->getPrevious()

set_exception_handler

Register a global uncaught exception handler:

<?php
set_exception_handler(function(\Throwable $e): void {
    error_log(sprintf(
        '[UNCAUGHT] %s: %s in %s:%d',
        get_class($e),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine()
    ));
    http_response_code(500);
    echo 'An unexpected error occurred. Please try again.';
    exit(1);
});

Quick Check

Which block in try/catch/finally is guaranteed to execute regardless of whether an exception is thrown?

Recap: try/catch/finally

Exception handling summary:

  • Throw exceptions with throw new ExceptionClass()
  • Catch with catch (Type $e)
  • Use multiple catch blocks for different types
  • finally always runs — use for cleanup
  • PHP 8 union catch: catch (A | B $e)
  • Re-throw to preserve call stack context

Frequently asked questions

Is the “Try, Catch, and Finally” lesson free?

Yes — the full text of “Try, Catch, and Finally” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Try, Catch, and Finally”?

Handle runtime exceptions gracefully with try/catch/finally blocks. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Try, Catch, and Finally” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. PHP Error Types and Reporting
  2. Try, Catch, and Finally
  3. Creating Custom Exceptions
  4. Logging Errors and Best Practices
← Back to PHP Academy