Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not catching PDOException in namespace

I can't know how can i catch PDOException in the follow code,please tell me where throw exception in the follow code?

i have (directory) :

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

 - autoloader

in the 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();
?>

and in 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>");
    }
}
}
?>

I enter wrong password,i expect that have catch the exception in my try catch block but have this output:

 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
like image 771
navid Avatar asked Nov 28 '12 21:11

navid


1 Answers

You are in a namespace. Hence, PHP will look for the namespaced class folder\PDOException and attempt to catch that (And fail).

To use the global namespace, simply add a backslash behind the class name:

catch (\PDOException $e) {
like image 84
Madara's Ghost Avatar answered Oct 21 '22 06:10

Madara's Ghost