本文介绍了不在命名空间中捕获PDOException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在下面的代码中捕获 PDOException ,请告诉我在下面的代码中throw throw在哪里?

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

我有(目录):

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

 - autoloader


b $ b

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


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

我输入错误的密码,我期望在我的 catch 阻止但具有以下输出:

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


推荐答案

您在命名空间中。因此,PHP将寻找名为空格的类 folder\PDOException ,并尝试捕获(和失败)。

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) {

这篇关于不在命名空间中捕获PDOException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 10:55