Martyn
Martyn

Reputation: 6403

Catch exception when on PDO connection

I have the following connection being made using PDO. Obviously it won't connect as I've not specified host or database (or user or password)

$dbh = new PDO('mysql:host=;dbname=', '', '');

..so how do I catch the exception? I'm trying something like this:

try {
  $dbh = new PDO('mysql:host=;dbname=', '', '');
} catch (Exception $e) {
  echo 'Error: ',  $e->getMessage(), "\n";
}

.. but no message is displayed. Why?

Upvotes: 0

Views: 1395

Answers (2)

Ali
Ali

Reputation: 151

Are you using custom namespace? then you need to change

} catch (\Exception $e) {
  echo 'Error: ',  $e->getMessage(), "\n";
}

notice the backslash before Exception.

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158250

You need to pass the attribute ERRMODE_EXCEPTION in order to receive exceptions on a failing connection attempt:

$dbh = new PDO('mysql:host=;dbname=', '', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));

Check the manual page of PDO::__construct() for more info.

Please also check @Ali's answer!

Upvotes: 0

Related Questions