federicot
federicot

Reputation: 12341

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(
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset"
    );

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

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

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

What am I missing here?

Upvotes: 6

Views: 3959

Answers (2)

xdazz
xdazz

Reputation: 160833

Turn on error_reporting and check the errors.

ini_set('display_errors', true);
error_reporting(E_ALL);

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

Upvotes: 2

ziad-saab
ziad-saab

Reputation: 20239

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

Upvotes: 24

Related Questions