0

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?

Martyn
  • 6,031
  • 12
  • 55
  • 121
  • Try adding `$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` right after the connection is opened. – Funk Forty Niner Jul 05 '14 at 11:26
  • 3
    Without specifying anything in the connection string, PDO will not attempt to connect to anything, thus no exception. Put anything in the connection string and you will see your exception. – John Jul 05 '14 at 11:31
  • Well if you want to catch PDO execption then catch `PDOException` instead of `Exception`.. makes sense? – meda Jul 05 '14 at 17:52

2 Answers2

3

Are you using custom namespace? then you need to change

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

notice the backslash before Exception.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Ali
  • 151
  • 11
  • 1
    -1 The echo syntax he is using is correct. (http://php.net/echo) And the exception namespace is ROOT so you do not need the slash – John Jul 05 '14 at 11:34
  • @John You are wrong with `And the exception namespace is ROOT so you do not need the slash`. If the code runs in a context of a custom namespace, the \ is required to address the global namespace. – hek2mgl Jul 05 '14 at 11:40
  • Where's the namespace he's using? He's not using one. You can also say maybe he has a database name of '' and a user of '' with a password of ''. It's a phantom solution that doesn't answer the question – John Jul 05 '14 at 11:42
  • @John Where would you expect the namespace declaration in that code snippet? It is likely that the code runs *indeed* in a custom namespace but the OP forgot to mention that – hek2mgl Jul 05 '14 at 11:45
0

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!

hek2mgl
  • 152,036
  • 28
  • 249
  • 266