What are the best practices for handling and displaying error messages in PHP applications to enhance security and user experience?

When handling and displaying error messages in PHP applications, it is important to avoid exposing sensitive information to potential attackers. To enhance security and user experience, it is recommended to display generic error messages to users while logging detailed error information for developers to troubleshoot.

// Example of handling and displaying error messages in PHP
try {
    // Code that may throw an exception
} catch (Exception $e) {
    error_log("An error occurred: " . $e->getMessage());
    echo "An error occurred. Please try again later.";
}