What are the best practices for handling errors and exceptions in PHP code?

When handling errors and exceptions in PHP code, it is important to use try-catch blocks to catch exceptions and gracefully handle errors. Additionally, logging errors to a file or database can help in debugging and monitoring the application. It is also recommended to provide informative error messages to users while avoiding revealing sensitive information about the system.

try {
    // Code that may throw an exception
    throw new Exception('An error occurred.');
} catch (Exception $e) {
    // Handle the exception gracefully
    echo 'An error occurred: ' . $e->getMessage();
    // Log the error to a file or database
    error_log('Error: ' . $e->getMessage(), 3, 'error.log');
}