没有在命名空间中捕获PDOException

时间:2012-11-28 21:11:42

标签: php database namespaces pdo

我不知道如何在以下代码中捕获PDOException,请告诉我在以下代码中抛出异常的位置?

我有(目录):

 - folder
     -1) b.php
     -2) c.php

 - autoloader
b.php中的

<?php
namespace folder;
use folder as x;
require_once '../autoload.php';
class b{
    function __construct(){
        print("<p>you are in class b<p/>");
    }
}
$t=new x\c();
?>

并在c.php中:     

class c{
    function __construct(){
        print("<p>you are in class c<p/>");

        if(DB_TYPE == 'mysql')  
        $pdoString=DB_TYPE.':dbname='.DB_NAME.';host='.DB_HOST;

        $pdoUsername=DB_USERNAME;
        $pdoPass='1';//DB_PASS; in this line I enter wrong password

    try{
            $this->pdo = new PDO($pdoString, $pdoUsername, $pdoPass);

    }catch(PDOException $e){ //we can't catch exception here!
        die('<p> Error DataBase Connection: '.$e->getMessage()."</p>");
    }
}
}
?>

我输入了错误的密码,我希望在我的try catch块中捕获异常,但是有这个输出:

 you are in class c

 Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)' in C:\xampp\htdocs\TEST\folder\c.php:17 Stack trace: #0 C:\xampp\htdocs\TEST\folder\c.php(17): PDO->__construct('mysql:dbname=kn...', 'root', '1') #1 C:\xampp\htdocs\TEST\folder\b.php(10): folder\c->__construct() #2 {main} thrown in C:\xampp\htdocs\TEST\folder\c.php on line 17

1 个答案:

答案 0 :(得分:13)

您在命名空间中。因此,PHP将查找命名空间类folder\PDOException并尝试捕获它(并失败)。

要使用全局命名空间,只需在类名后面添加一个反斜杠:

catch (\PDOException $e) {