1. Basic Error Handling with try, catch, and finally
PHP supports exception handling using try, catch, and finally blocks. This allows you to catch and handle exceptions gracefully.
<?php
try {
// Code that may throw an exception
$result = 10 / 0;
echo "This line will not be executed.";
} catch (Exception $e) {
// Handle the exception
echo "Caught exception: " . $e->getMessage();
} finally {
// Code that will be executed regardless of whether an exception was thrown
echo "Finally block executed.\n";
}
?>2. Custom Error Handler Function
You can set a custom error handler function using set_error_handler. This function will be called for all errors that PHP encounters.
<?php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Custom error handler: [$errno] $errstr in $errfile on line $errline\n";
}
// Set custom error handler
set_error_handler("customErrorHandler");
// Trigger an error
echo $undefinedVariable;
?>3. Error Reporting Level
Adjusting the error reporting level using error_reporting can help control which types of errors are displayed or logged.
<?php // Report all errors except notices error_reporting(E_ALL & ~E_NOTICE); // Trigger a notice (won't be displayed) echo $undefinedVariable; ?>
4. Logging Errors
Configuring PHP to log errors is essential for debugging in a production environment. You can set the error_log directive in the php.ini file or dynamically in your script.
<?php
// Log errors to a file
ini_set("log_errors", 1);
ini_set("error_log", "/path/to/error.log");
// Trigger an error
echo $undefinedVariable;
?>5. Exception Handling in Object-Oriented Code
In object-oriented code, you can create custom exception classes and throw them when necessary.
<?php
class CustomException extends Exception {}
try {
throw new CustomException("This is a custom exception.");
} catch (CustomException $e) {
echo "Caught custom exception: " . $e->getMessage();
}
?>6. Displaying Errors
In a development environment, it’s useful to display errors on the screen. However, in a production environment, it’s recommended to log errors and display a generic error message to users.
<?php
// Display errors on the screen (in development)
ini_set("display_errors", 1);
// Log errors to a file (in production)
ini_set("log_errors", 1);
ini_set("error_log", "/path/to/error.log");
// Trigger an error
echo $undefinedVariable;
?>Choose the error handling approach that best fits your application’s requirements and the development or production environment. Remember to handle errors gracefully to provide a better user experience and facilitate troubleshooting during development.

