As we have seen previously, we place the try...catch blocks around code that can throw exceptions. However, in very rare cases, there might be some unexpected exceptions. We can imitate such an exception by modifying one of the queries so that it contains some malformed SQL. For example, let's edit authors.php
, line 16 to the following:
$q = $conn->query("SELECT * FROM authors ORDER BY lastName, firstName");
Now try to navigate to authors.php
with your browser to see that an uncaught exception has occurred. To correctly handle this situation, we either should create an exception handler or wrap every block of code that calls PDO
or PDOStatement
class methods in a try…catch block.
Let's see how we can create the exception handler. This is an easier approach as it does not require changing lots of code. However, for big applications this may be bad practice as handling exceptions, where they occur may be more secure and better recovery logic can be applied...