PHP PDO supports powerful exception handling mechanisms that help developers catch and manage database-related errors safely using try-catch blocks.
By enabling exception mode in PDO, database errors throw exceptions instead of failing silently. This ensures controlled error handling and better debugging.
// Demonstrates PDO connection and query with exception handling
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT id, name FROM users");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
}
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage();
}
?>
If the database connection or query fails, the script safely displays an error message instead of crashing.
Change the database name intentionally and observe how the exception is triggered and handled gracefully.