Coding/Learn/php/php exceptions and error handling
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnExceptions, Throwables & Custom Error Fences
13 / 20 0%
Lesson 13 of 20
9 mins read

Exceptions, Throwables & Custom Error Fences

PreviousNext Lesson
In Plain English

Modern PHP handles errors and exceptions through the unified Throwable interface. Learn try...catch...finally blocks, throwing custom Exception classes, catching multiple exception types, and global error handling.

The Mental Model

"An exception is like an emergency stop cord on a train. When an impossible condition occurs (out of funds, database down), the conductor pulls the cord (throw), and the emergency response team (catch) safely evacuates passengers without a derailment."

Deep Dive: How It Works

The Throwable Hierarchy: Both Exception and Error (e.g. TypeError, ParseError) implement the Throwable interface.

Try-Catch-Finally: try runs code; catch intercepts matching exception types; finally executes cleanup unconditionally.

Custom Exceptions: Create domain exceptions by extending Exception (e.g. class PaymentFailedException extends Exception {}).

Exception Chaining: throw new ServiceException("Lookup failed", 0, $previousException) preserves root cause.

Syntax Blueprint

<?php

try {
    throw new InvalidArgumentException("Port must be positive");
} catch (InvalidArgumentException $e) {
    echo "Handled: " . $e->getMessage();
} finally {
    // Guaranteed cleanup
}

Wrap risky code in try blocks, handle specific exceptions in catch, and release resources in finally.

PointCore Rules to Remember

Point star
Catch Throwable: Catch Throwable to intercept both userland exceptions and PHP internal engine Errors.
Point star
Multiple Catch Blocks: Order catch blocks from most specific exception type to most generic.
Point star
Union Exceptions (PHP 8): catch (DbException | NetworkException $e) handles multiple exception types in a single block.

Common Beginner Traps & How to Fix Them

Mistake:Using empty catch (Exception $e) {} blocks that silently swallow errors.

Why it happens: Hides critical system failures and makes debugging impossible.

How to fix: Always log exceptions (error_log) or rethrow them if unrecoverable.

Pro Tip: Convert legacy PHP notices and warnings to ErrorException using set_error_handler() for 100% exception-driven architectures.

Live Interactive Example

Hit Run Code to see it live
Custom Exception and Safe Recovery Fence
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Output Console
Click "Run Code" to view the rendered output.
How it works: The invalid email threw ValidationException, safely intercepted by catch, followed by finally execution.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Throw and Catch Division by Zero Exception

  • PointWrite a function safeDivide(float $a, float $b): float.
  • PointIf $b == 0.0, throw new InvalidArgumentException("Division by zero").
  • PointReturn $a / $b.
  • PointWrap a call to safeDivide(10, 0) in a try-catch block and print "Error: " followed by the exception message.
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates