Does PDO fetch() throw an exception on failure?

Viewed 746

Does the method PDOStatement::fetch() throw an exception on failure, if the PDO error reporting system is set to throw exceptions? E.g. if I set:

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION

Do you know such a case?

Thank you very much.


UPDATE:

The method PdoStatement::fetch throws indeed exceptions on failure, instead of FALSE. Such a case is demonstrated in my answer:

In conclusion:

  • PDOStatement::fetch returns FALSE if no records are found.
  • PDOStatement::fetch throws exceptions on failure.
2 Answers

There is a user note on the page you mentioned in your question which says:

WARNING: fetch() does NOT adhere to SQL-92 SQLSTATE standard when dealing with empty datasets.

Instead of setting the errorcode class to 20 to indicate "no data found", it returns a class of 00 indicating success, and returns NULL to the caller.

This also prevents the exception mechainsm from firing.

Programmers will need to explicitly code tests for empty resultsets after any fetch*() instead of relying on the default behavior of the RDBMS.

I tried logging this as a bug, but it was dismissed as "working as intended". Just a head's up.

According to this note the answer to your question is NO.

Update:
Accepted answer mentions a bug which is marked as fixed and the test code provided in bug report does not result in an exception being thrown anymore. It was actually fixed back in 2007.

The user here claims that fetch() threw an exception. I'd be very careful in assuming that it doesn't or won't throw an exception just because they are typically thrown when you prepare or bind. This is a very good reason to put the call inside a try block. So to answer the question, in the highly unlikely event of failure, yes fetch() should throw an exception and in that one case it did. Now it will be interesting to see if there are other cases as well.

Related