How can PHP error reporting and error handling be optimized for better troubleshooting?

To optimize PHP error reporting and error handling for better troubleshooting, you can enable error reporting, log errors to a file, and use try-catch blocks to handle exceptions gracefully.

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log errors to a file
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');

// Use try-catch blocks to handle exceptions
try {
    // Code that may throw an exception
} catch (Exception $e) {
    // Handle the exception
    echo 'Caught exception: ' . $e->getMessage();
}