PDOException not being caught?

I’m getting the following error in PHP:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'localhost' (10061)' in C:\xampp\htdocs\project\Service\Database.class.php:26 Stack trace: #0 C:\xampp\htdocs\project\Service\Database.class.php(26): PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 C:\xampp\htdocs\project\Service\Database.class.php(54): Service\Database::initialize() #2 C:\xampp\htdocs\project\index.php(15): Service\Database::getHandler() #3 {main} thrown in C:\xampp\htdocs\project\Service\Database.class.php on line 26

The error itself is not the problem, I intentionally terminated the MySQL service in Windows to see what happened (I’m using XAMPP). The problem is that I’m unable to catch the exception that the PDO object throws and I don’t know why.

try {
    $host       = "localhost";
    $dbname     = "project";
    $userName   = "root";
    $password   = "";
    $charset    = "utf8";
    $dsn        = "mysql:host=$host;dbname=$dbname;charset=$charset";

    $driverOptions = array(

    // This is the line that supposedly throws the exception (LINE 26):
    $dbh = new PDO($dsn, $userName, $password, $driverOptions);


} catch (PDOException $e) {
    die("CATCHED"); // This line is never reached
} catch (Exception $e) {
    die("CATCHED"); // nor this one.

What am I missing here?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The only thing I can think of is if you’re inside a namespaced class, and should use \PDOException instead of PDOException.

Solution 2

Turn on error_reporting and check the errors.

ini_set('display_errors', true);

May be there is a fatal error, before that line, or maybe PDO is not available.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply