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
119: Custom Exception Classes Revisited
I see this all the time in code reviews: a developer creates a dozen different exception classes, but every single one of them is just an empty class that extends \Exception. They'll have a UserNotFoundException, a DatabaseConnectionException, and a InvalidInputException, but none of them actually do anything different from the base exception.
Custom Exceptions are just for better naming
The misconception here is that the primary purpose of a custom exception is to give the error a descriptive name so the logs look prettier. If that's all you're doing, you're essentially just creating "tags" for your errors. While that's not technically wrong, it's a waste of your time and adds unnecessary boilerplate to your project. Look at this:
// This is basically useless
class OrderNotFoundException extends \Exception {}
// Later in the code...
throw new OrderNotFoundException("Order #123 not found");
If your only reaction to this exception is to catch it and display the message to the user, you didn't need a custom class. A standard \Exception or a \RuntimeException would have behaved exactly the same way. You've added a file to your project without adding any actual functionality.
Exceptions as Data Carriers for Recovery Logic
The real power of custom exceptions kicks in when you treat them as data objects. An exception shouldn't just tell you that something went wrong; it should provide the necessary context for the catch block to actually fix the problem or make an informed decision about what to do next.
Let's imagine we're building a payment integration. If a payment fails, "Payment failed" is a useless message for a programmer. Did it fail because the card expired? Because there were insufficient funds? Or because the API is down? Each of those requires a different response from the application.
class PaymentFailedException extends \Exception
{
private string $gatewayErrorCode;
private bool $isRetryable;
public function __construct(string $message, string $gatewayErrorCode, bool $isRetryable)
{
parent::__construct($message);
$this->gatewayErrorCode = $gatewayErrorCode;
$this->isRetryable = $isRetryable;
}
public function getGatewayErrorCode(): string
{
return $this->gatewayErrorCode;
}
public function shouldRetry(): bool
{
return $this->isRetryable;
}
}
Now, look at how this changes your handling logic. You aren't just catching a "name"; you're accessing state to drive your application's behavior:
try {
$paymentProcessor->charge($amount);
} catch (PaymentFailedException $e) {
if ($e->shouldRetry()) {
// Log it and trigger an automatic retry after 5 minutes
$this->queueRetry($orderId);
} else {
// Tell the user exactly why they need to change their card
$this->notifyUser($e->getGatewayErrorCode());
}
}
I've found that this approach separates the detection of the error (the service throwing the exception) from the strategy for handling it (the controller or command catching it). The service knows why it failed, but it shouldn't decide how the app recovers. By attaching that data to the exception, you pass the "why" up the chain without polluting your business logic with `if/else` blocks inside your API clients.
One last tip: don't be afraid to create an exception hierarchy. You can have a base PaymentException and then have InsufficientFundsException and ExpiredCardException extend that. This allows you to catch all payment errors in one block, or target a specific one if you have a very specialized recovery path for it.
📋 Practical Task
Implementing a Tiered Exception System for a File Upload Manager
You are building a file upload system. Instead of using generic exceptions, you need to implement a system that allows the calling code to distinguish between a "User Error" (which should be shown to the user) and a "System Error" (which should be logged and trigger an admin alert).
Requirements:
- Create a base exception class
UploadException. - Create two child classes:
InvalidFileException(for user errors like wrong file type) andStorageLimitException(for system errors like disk full). - The
InvalidFileExceptionmust include a methodgetAllowedTypes()that returns an array of strings. - The
StorageLimitExceptionmust include a methodgetAvailableSpace()that returns the remaining bytes. - Write a
try/catchblock that handlesInvalidFileExceptionby printing the allowed types, and handlesStorageLimitExceptionby logging a "Critical System Error" message.
There are no comments for now.