Errors and exceptions are inevitable in any programming language, but handling them properly is crucial for creating robust and user-friendly applications. In this lesson, we'll explore error and exception handling in PHP, including the use of try-catch blocks and custom exception classes.
By default, PHP displays errors and warnings on the web page, which can be helpful during development but may expose sensitive information in a production environment. You can control how PHP handles errors using the error_reporting()
function and ini_set()
function.
// Disable all error reporting
error_reporting(0);
// Enable all error reporting
error_reporting(E_ALL);
// Display errors on the web page
ini_set("display_errors", 1);
// Log errors to a file
ini_set("log_errors", 1);
ini_set("error_log", "/path/to/error.log");
Exceptions are used to signal exceptional conditions that require special handling. You can use the try-catch block to handle exceptions.
try {
// Code that may throw an exception
if ($denominator == 0) {
throw new Exception("Division by zero is not allowed.");
}
$result = $numerator / $denominator;
} catch (Exception $e) {
// Handle the exception
echo "Error: " . $e->getMessage();
}
You can create custom exception classes by extending the base Exception
class. This allows you to define more specific exception types and add additional properties or methods.
class DivisionByZeroException extends Exception {
public function __construct($message = "Division by zero is not allowed.", $code = 0, Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
}
try {
if ($denominator == 0) {
throw new DivisionByZeroException();
}
$result = $numerator / $denominator;
} catch (DivisionByZeroException $e) {
echo "Error: " . $e->getMessage();
}
The optional finally block allows you to execute code regardless of whether an exception was thrown or not. This can be useful for cleanup tasks, such as closing database connections or file handles.
try {
// Code that may throw an exception
} catch (Exception $e) {
// Handle the exception
} finally {
// Code to be executed regardless of whether an exception was thrown or not
}
Practice error and exception handling in PHP by completing the following exercises: