phpPHP
Module 20: Error HandlingIntermediate45 min read

PHP Error Model, Throwable Hierarchy, Custom Exceptions & Production Logging

Master PHP's Throwable hierarchy (Error vs Exception), try/catch/finally, custom domain exceptions, and why display_errors must be Off in production.

Key Takeaways & Core Concepts
  • Master PHP's Throwable hierarchy (Error vs Exception), try/catch/finally, custom domain exceptions, and why display_errors must be Off in production.
  • Practice writing and running standard examples.
  • Apply best practices and debugging techniques.

1. `Throwable` Hierarchy

Both Error (internal engine errors like TypeError, UnhandledMatchError) and Exception (application-level) implement Throwable.

1. try / catch / finally with Custom Exception
1<?php
2class ValidationException extends RuntimeException {}
3
4function validateAge(int $age): void {
5 if ($age < 18) throw new ValidationException("Must be 18+");
6}
7
8try {
9 validateAge(15);
10} catch (ValidationException $e) {
11 echo "Validation failed: " . $e->getMessage() . "\n";
12} finally {
13 echo "Cleanup complete.\n";
14}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
14 lines
Note: `finally` executes deterministically whether an exception was thrown or not.

2. Production Safety

Never expose stack traces or display_errors = On in production—attackers use paths and SQL details for reconnaissance. Log errors securely via error_log() or Monolog and return generic HTTP 500 messages.

Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)