7

我不知道如何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
4

1 回答 1

16

你在一个命名空间中。因此,PHP 将寻找命名空间类folder\PDOException并尝试捕获它(但失败)。

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

catch (\PDOException $e) {
于 2012-11-28T21:13:45.780 回答