When working with PHP classes, what are some best practices for handling exceptions like PDOExceptions in methods that interact with databases?

When working with PHP classes that interact with databases, it is important to handle exceptions like PDOExceptions properly to ensure robust error handling. One best practice is to catch the exceptions within the method that interacts with the database and handle them accordingly, which may involve logging the error, displaying a user-friendly message, or rolling back transactions. This helps in maintaining the integrity of the application and providing a better user experience.

class DatabaseHandler {
    private $pdo;

    public function __construct($dsn, $username, $password) {
        $this->pdo = new PDO($dsn, $username, $password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function fetchData($query) {
        try {
            $statement = $this->pdo->prepare($query);
            $statement->execute();
            return $statement->fetchAll();
        } catch (PDOException $e) {
            // Log the error or handle it in a way that suits your application
            error_log("Database error: " . $e->getMessage());
            // Optionally, rethrow the exception to propagate it up the call stack
            throw $e;
        }
    }
}