Do I need to use the try and catch block to display errors with PHP's PDO extension?
For example, with mysql you can usally do something like:
if ( ! $query)
{
die('Oh noes!');
}
You can choose what PDO does with errors via PDO::ATTR_ERRMODE:
$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Raise E_WARNING.
$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); // Sets error codes.
// or
$pdo->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // throws exception
PDO by default supports it's own Exception Class, PDOException.
There should be no reason why you cannot use:
try{
$query = $db->prepare(...);
if( !$query ){
throw new Exception('Query Failed');
}
}
catch(Exception $e){
echo $e->getMessage();
}
The reason I only catch Exception is because PDOException is a child of Exception. Catching the Parent will catch ALL children.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With