What are the advantages of using try/catch blocks when working with PDO and ERRMODE_EXCEPTION in PHP?

When working with PDO in PHP, setting ERRMODE_EXCEPTION allows PDO to throw exceptions when errors occur, making it easier to handle and debug issues. By using try/catch blocks, you can catch these exceptions and gracefully handle them, such as displaying an error message to the user or logging the error for later review.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Perform database operations here
    
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}