PHP 8: Modern PHP Development · Errors, Exceptions and Robust Code

Exceptions and the Throwable Hierarchy

Understand Error vs Exception, custom exceptions, finally and exception chaining.

Everything thrown in PHP 8 implements Throwable. Exception is for conditions your code can anticipate and handle (invalid input, missing records, failed HTTP calls); Error covers engine problems such as TypeError, ValueError, ArgumentCountError and DivisionByZeroError. Many functions that used to return false or emit warnings now throw TypeError/ValueError in PHP 8. Create domain-specific exceptions, chain the cause with the $previous argument, and use finally for cleanup.

<?php
final class PaymentFailed extends RuntimeException
{
    public static function fromGateway(string $reason, ?Throwable $previous = null): self
    {
        return new self("Payment failed: {$reason}", previous: $previous);
    }
}

try {
    $result = $gateway->charge($amount, $token);
} catch (HttpTimeout $e) {
    throw PaymentFailed::fromGateway('timeout', $e);   // keep the cause
} catch (CardDeclined $e) {
    return Response::paymentRequired($e->getMessage());
} finally {
    $lock->release();
}

Common pitfalls

  • Catching Throwable or Exception broadly and swallowing errors silently.
  • Losing the original cause by not passing $previous.
  • Using exceptions for normal control flow in hot loops.

Key points

  • Error = engine problems; Exception = recoverable conditions
  • Chain causes with previous
  • Catch specific types at the right layer

Further reading: PHP manual: exceptions

Practice questions

What's the difference between Error and Exception in PHP 8?

Answer

Both implement Throwable. Error represents engine-level problems (type errors, calling undefined methods, division by zero), while Exception represents application conditions you expect to handle. Catch Throwable only at top-level boundaries.

Why pass the original exception as previous?

Answer

It preserves the root cause and its stack trace so logs show both the high-level failure and the underlying error (e.g., the timeout behind a PaymentFailed).

Open in the app to mark lessons complete, take notes and track your progress.