Error & Exception Handling
7 questions foundWhat is the difference between a PHP error and a PHP exception?
Beginner A PHP error traditionally represents a problem detected by the PHP engine itself, such as calling an undefined function, and historically these were handled differently from exceptions, while an exception is an object representing an exceptional condition that your own code or a library deliberately throws, and can be caught and handled gracefully using a try catch block, with modern PHP versions unifying much of this behavior so that many previously fatal errors are now also represented as catchable Error objects implementing the same Throwable interface as exceptions.
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo 'Cannot divide by zero';
}
Real-world example A calculation function safely catches a DivisionByZeroError, which in older PHP versions would have been an uncatchable fatal error, allowing the application to display a friendly error message instead of crashing entirely.
Common follow-ups: What is the Throwable interface and how do Error and Exception both relate to it?;What are some common built in exception classes provided by PHP?
OOP;Basics & Types
How does a try catch block work in PHP, and how do you catch and handle a specific exception that might be thrown?
Beginner A try catch block lets you wrap code that might throw an exception inside a try section, and if an exception occurs, execution immediately jumps to a matching catch block that specifies the type of exception it handles, letting you respond to that specific error condition, such as displaying a user friendly message or logging the issue, without the entire script crashing due to an unhandled exception.
try {
$data = json_decode($jsonString, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo 'Invalid JSON: ' . $e->getMessage();
}
Real-world example An API endpoint that parses incoming JSON data wraps the parsing logic in a try catch block, gracefully returning a clear error message to the client if the submitted JSON is malformed, rather than the entire request failing with an unhandled error.
Common follow-ups: Can a single try block have multiple catch blocks for different exception types?;What is the difference between catching a specific exception type versus a general Exception?
JSON Handling in PHP;RESTful API Development with PHP
How does the finally block work alongside try and catch, and what are appropriate use cases for it?
Intermediate A finally block contains code that always executes after the try and any matching catch block, regardless of whether an exception was thrown or caught, making it well suited for cleanup tasks that must always happen, such as closing a file handle or a database connection, ensuring those necessary cleanup steps run whether the preceding code succeeded, failed, or even if the code inside the catch block itself throws a new exception.
$file = fopen('data.txt', 'r');
try {
processFile($file);
} catch (Exception $e) {
logError($e);
} finally {
fclose($file);
}
Real-world example A file processing function ensures the opened file handle is always closed in a finally block, guaranteeing proper resource cleanup regardless of whether the actual file processing succeeded or threw an exception partway through.
Common follow-ups: What happens if the finally block itself throws an exception?;Is a finally block always guaranteed to execute even if the try block returns a value?
File Handling & File System Functions;OOP
How do you create and throw a custom exception class in PHP, and why would you define your own exception types instead of using PHP's built in generic Exception class?
Intermediate You create a custom exception by defining a class that extends PHP's built in Exception class, or a more specific built in exception, optionally adding your own additional properties or methods, and defining custom exception types lets calling code catch and respond to very specific error conditions distinctly, such as differentiating between an InsufficientFundsException and a generic database error, rather than needing to inspect a generic exception's message text to determine what actually went wrong.
class InsufficientFundsException extends Exception {
public function __construct(private float $shortfall) {
parent::__construct("Insufficient funds, short by $shortfall");
}
public function getShortfall(): float { return $this->shortfall; }
}
Real-world example A banking application throws a custom InsufficientFundsException when a withdrawal exceeds the available balance, letting the calling code specifically catch this exception type and display a precise, helpful message rather than a generic error.
Common follow-ups: Should custom exceptions extend the base Exception class or a more specific built in exception like InvalidArgumentException?;How many custom exception classes is reasonable for a typical application to define?
OOP;Design Patterns in PHP
What is exception chaining in PHP, and how does the previous exception parameter help preserve the original context when re throwing an error?
Intermediate Exception chaining lets you pass an original exception as the previous parameter when constructing and throwing a new exception, preserving the full chain of what actually caused the error even as it gets wrapped in higher level, more descriptive exception types as it propagates up through different layers of your application, which is extremely valuable for debugging since you can trace the exact root cause rather than only seeing the final, more generic exception message.
try {
$pdo->query($sql);
} catch (PDOException $e) {
throw new DatabaseException('Failed to fetch user data', previous: $e);
}
Real-world example A developer investigating a reported bug traces a high level DatabaseException all the way back to its original underlying PDOException using the exception chain, immediately identifying the specific SQL error that ultimately caused the problem.
Common follow-ups: How do you access the previous exception from within a catch block?;Does exception chaining affect the stack trace shown when logging an error?
PDO & Databases;Error & Exception Handling
How do you set a global exception handler and error handler in PHP to consistently catch and log any uncaught exceptions or errors across an entire application?
Advanced PHP provides set_exception_handler and set_error_handler functions that let you register custom functions to be called automatically whenever an uncaught exception occurs or a PHP error is triggered anywhere in your application, providing a centralized place to consistently log these issues, notify a monitoring service, and display a generic, user friendly error page, rather than relying on every single piece of code to individually handle every possible error condition.
set_exception_handler(function (Throwable $e) {
error_log($e->getMessage());
http_response_code(500);
echo 'Something went wrong';
});
Real-world example A production application registers a global exception handler that automatically logs every uncaught exception to a monitoring service and displays a generic error page to the user, ensuring no unhandled error ever exposes sensitive internal details or a raw stack trace to an end user.
Common follow-ups: How do modern frameworks like Laravel and Symfony implement this kind of centralized exception handling?;What is the difference between set_exception_handler and set_error_handler?
Security;Deployment & Hosting for PHP Applications
What best practices should guide how an application logs, reports, and responds to exceptions differently across development and production environments?
Advanced In a development environment, it is generally helpful to display detailed exception messages and full stack traces directly to the developer to speed up debugging, while in production, detailed technical error information should never be shown directly to end users since it could reveal sensitive internal implementation details, and instead the application should log the full detailed error information to a secure logging system or monitoring service while showing users only a generic, friendly error message, striking the right balance between developer visibility and production security.
if (app()->environment('local')) {
// Show detailed error page with stack trace
} else {
// Log full details, show generic error message to user
Log::error($exception);
}
Real-world example A company's production application logs full exception details, including stack traces, to a centralized error monitoring service while showing users only a friendly apology message, ensuring developers still have everything they need to diagnose issues without exposing sensitive information publicly.
Common follow-ups: What sensitive information could accidentally be exposed by a detailed error page in production?;How do popular PHP frameworks differentiate error display behavior based on the environment automatically?
Security;Deployment & Hosting for PHP Applications