PHP “Exception not found”

<?php namespace MyProject;
header("Content-Type: text/html; charset=utf-8");
error_reporting(0);
function theDataBaseObj()
{
    $mysql = mysql_connect("localhost","roost","root","9096");
    if($mysql){
        return $mysql; 
    }else{

        throw new Exception("Error Connect");
    }
}
function db()  
{
    try{
        $db = \MyProject\theDataBaseObj();
        echo("success");
        var_dump($db);
    }catch(Exception $e){
        echo("error");
        var_dump($e->getMessage());
    }
}
db();
?>

看陈小龙的PHP7实践指南的时候遇到的这个问题,如果成功还无所谓,但是如果你连接数据库失败的话,问题就出现了,你会发错误码255,页面并不会打印出任何东西。

于是很纠结的去翻了翻blog ,文章。
stack overflow上有一个方案解决。

就是添加一下 use Exception 使用原生的Exception ,否则会出现Exception not found;

<?php namespace MyProject;
header("Content-Type: text/html; charset=utf-8");
use Exception;//看这里,看这里
error_reporting(0);
function theDataBaseObj()
{
    $mysql = mysql_connect("localhost","roost","root","9096");
    if($mysql){
        return $mysql; 
    }else{

        throw new Exception("Error Processing Request");
    }
}
function db()  
{
    try{
        $db = \MyProject\theDataBaseObj();
        echo("success");
        var_dump($db);
    }catch(Exception $e){
        echo("error");
        var_dump($e->getMessage());
    }
}
db();
?>

发布了96 篇原创文章 · 获赞 74 · 访问量 23万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章