What is the difference between PDO::ERRMODE_EXCEPTION and PDO::ERRMODE_SILENT?
( http://php.net/manual/en/pdo.error-handling.php ) I tried both, but both threw exceptions. (At least when I tried them while turning off my database to database errors). So I couldn’t find the a difference between them. Both exceptions ended up in my php error log. I thought PDO::ERRMODE_SILENT didn’t throw exceptions, so PDO code would not have to be in try/catch blocks, but if it also throws exceptions, what is the difference?

Did PHP actually catch an exception with both executions? What code did you use to test this?

Something like this:

$pdo = new PDO('MY DB CONFIG');

I turned the database on and off (mysql) and tested it with both.

PDO always throws an Exception when it cannot successfully connect to the DB, no matter which error handling you set:

1 Like

So you told it to construct a bad object.
At which point it immediately exceptioned.
THEN you tried to tell it to go silent. But… the exception has already occurred. So… yeah.

The system cannot tell you’re going to tell it to go silent on the second line of code before it actually finishes executing the first line of code.

I thought that might be happening, but wasn’t sure because I am not sure about manipulating PDO very well (working on it).

I found that no code I tried prevents PDO from throwing an error if an error occurs during the constructor.
Even this, passed in, doesn’t work:

$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));

But PDO::ERRMODE_SILENT does work if the PDO object is constructed successfully. It does not throw exceptions for bad queries and errors are not logged to php_error_log.

The manual does mention this, but I missed it because it’s actually hidden between two examples, instead of at the top where it should be.

PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set. Uncaught Exceptions are fatal.

Thanks for the help, both of you.

1 Like

so the only way to not throw an exception when connecting fail is to catch it?

Why would you want to do that? If you have no connection, then there is no point in proceeding with the code. Exceptions are a comfortable way of skipping arbitrary code without the need of piping return values.

1 Like

I was just curios.
because I thought PDO::ERRMODE_SILENT will work even if there is no connection.

the manual explicitly states otherwise. cf. post #4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.