I’m using PDO to connect to a mysql database. I’m confused as to where I should be using try catch blocks if I set the error attribute like so:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Right now I have my connection info (username, pass, etc) and the line above in a separate file that I will include in my main files. These (connection info and the line above) are stored in a try-catch block.
In my main files, I include this file. Do I need try-catch blocks in my main files too (around pdo related stuff)? (They are where I create and execute queries).
As with all exceptions, you’ll need to handle them anytime they’re not handled and at a place it makes sense to handle them. For each method that may throw, ask yourself where could it conceivably be handled properly? It may not make sense to catch exceptions right when the PDO functions that may throw them are called, but at a higher level. (For example, it doesn’t make sense to handle a PDOException at the point a new PDO object is created, as the code that follows will depend on having a valid PDO object; instead, it must be handled at a point that can either attempt to recover from the exception or fail gracefully.) This is the reason for exceptions: errors may be detected at a lower level, where there may not be sufficient information to deal with the error. So, the code throws an exception to somewhere higher that can deal with the error.
In a well designed project, datastore access is sequestered away into a module, so most of the rest of the code is unaffected by the exact nature of the datastore. In architectures that have this separation (such as multi-tiered or MVC), the datastore exceptions would be handled in the data access layer, though “handling” may mean throwing a different type of exception.
It helps to think about exception handling strategies:
or diewhen outputting HTML; invalid HTML isn’t graceful).See also: “Exception-handling antipatterns“.
If you’re asking whether setting the error mode to
PDO::ERRMODE_EXCEPTIONwill cause exceptions to be caught, then no; just the opposite, in fact. Only catch blocks can handle exceptions.