PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
118: The Exception Class Hierarchy in PHP
By now, you're comfortable wrapping risky code in a try-catch block. But if you look at a lot of legacy PHP projects, you'll see a pattern that I call "The Catch-All Vacuum." It's the habit of throwing the base \Exception class for every single thing that goes wrong. When you're first starting out, it feels efficient. Why bother creating five different classes when throw new \Exception("Invalid API key") does the trick? The problem is that you're throwing away the most valuable part of an exception: its type.
The Trap of the Generic Exception
Imagine we're building a payment processing module. If you use the naive approach, your code probably looks something like this:
function processPayment($amount, $cardDetails) {
if (!$cardDetails->isValid()) {
throw new \Exception("Invalid card details");
}
if ($amount > $cardDetails->getBalance()) {
throw new \Exception("Insufficient funds");
}
if (!PaymentGateway::ping()) {
throw new \Exception("Gateway timeout");
}
}
At first glance, this is fine. But look at it from the perspective of the code calling this function. If you want to handle a "balance too low" error differently than a "server is down" error, you're forced to do something truly hideous: you have to catch the exception and then perform string matching on the message.
try {
processPayment(100, $card);
} catch (\Exception $e) {
if ($e->getMessage() === "Insufficient funds") {
// Ask user for a different card
} elseif ($e->getMessage() === "Gateway timeout") {
// Retry in 5 seconds
} else {
// Log a critical system failure
}
}
I can't stress enough how fragile this is. The moment a teammate changes "Insufficient funds" to "Insufficient balance" in the processPayment function, your error handling silently breaks. You've turned your type-safe language into a guessing game of string comparisons.
Categorizing Errors for Better Control
The professional way to handle this is to leverage the Exception hierarchy. PHP provides several built-in SPL (Standard PHP Library) exceptions, but for your own business logic, you should build your own tree. I usually start by creating a base exception for the entire module, and then specialize from there.
In our payment example, we'd create a PaymentException that extends the base \Exception. Then, we create specific children for different categories of failure. For instance, PaymentValidationException (for user errors) and PaymentNetworkException (for infrastructure errors).
class PaymentException extends \Exception {}
class PaymentValidationException extends PaymentException {}
class PaymentNetworkException extends PaymentException {}
function processPayment($amount, $cardDetails) {
if (!$cardDetails->isValid()) {
throw new PaymentValidationException("Invalid card details");
}
if ($amount > $cardDetails->getBalance()) {
throw new PaymentValidationException("Insufficient funds");
}
if (!PaymentGateway::ping()) {
throw new PaymentNetworkException("Gateway timeout");
}
}
Now, the hierarchy does the heavy lifting for you. You can catch the most specific error first, and let the more general ones fall through to a broader handler. It's much cleaner, and it's completely immune to changes in the error message text.
Where the Architecture Actually Wins
You might be thinking, "This is just more files to manage." And you're right; it is. But the trade-off is a massive gain in architectural clarity. Look at how the calling code transforms:
try {
processPayment(100, $card);
} catch (PaymentValidationException $e) {
// We know this is a user-fixable error. Show a friendly message.
echo "Please check your payment details: " . $e->getMessage();
} catch (PaymentNetworkException $e) {
// This is a technical glitch. Log it and suggest a retry.
Log::error($e->getMessage());
echo "Our payment provider is struggling. Try again in a moment.";
} catch (PaymentException $e) {
// This catches any other payment-related error we didn't specifically target.
echo "A payment error occurred.";
} catch (\Throwable $e) {
// This is the ultimate safety net for non-payment crashes (like TypeErrors).
echo "A critical system error occurred.";
}
By using a hierarchy, you've created a filtering system. You've separated "user mistakes" from "system failures" without ever having to read a single string of text. This is how you build a system that doesn't collapse the moment you decide to translate your error messages into another language or tweak a typo.
📋 Practical Task
Exercise: Implementing a Tiered Library Exception Hierarchy
You are building a File Management Library. Currently, the library throws generic \Exception objects for everything, making it impossible for the implementing developer to distinguish between a file that is missing and a file that the system doesn't have permission to read.
Your Task:
- Create a base exception class called
FileLibException. - Create two specialized child classes:
FileNotFoundExceptionandFilePermissionException. - Write a function
readFileContents($path)that:- Throws a
FileNotFoundExceptionif the file does not exist (usefile_exists()). - Throws a
FilePermissionExceptionif the file exists but is not readable (useis_readable()). - Returns the file contents if both checks pass.
- Throws a
- Implement a
try-catchblock that handlesFileNotFoundExceptionby suggesting a default file path, handlesFilePermissionExceptionby logging a security warning, and handles all otherFileLibExceptionerrors with a generic "File system error" message.
There are no comments for now.