2014-03-31 133 views
0

当我试图用database->Select测试我的try-catch块时,我期待在尝试回显PDO语句时捕获异常,但它告诉我错误未被捕获。php尝试捕获不捕获异常

Catchable fatal error: Object of class PDOStatement could not be converted to string

我不明白我在做什么错在这里。

下面是代码:

class database{ 

    private $conn; 
    private $sqlError; 

    public function __construct() { 
     $server = "localhost"; 
     $username = "user"; 
     $pass = "password"; 
     $database = 'dbname'; 
     $dsn = sprintf('mysql:dbname=%s;host=%s', $database, $server); 
     try { 
      $this->conn = new PDO($dsn, $username, $pass); 
     } catch (Exception $exc) { 
      $this->sqlError = 'SQL Error: ' . $exc->getCode(); 
     } 
    } 

    public function Select($query, $values=array()) { 
     unset($this->sqlError); 
     try { 
      $qry = $this->conn->prepare('select ' . $query); 
      echo $qry; //invalid operation, I expect exception to be thrown 
      $qry->execute($values); 
      $result = $qry->fetchAll(PDO::FETCH_OBJ); 
      $error = $qry->errorInfo(); 
      if ($error[1]) { 
       $this->sqlError = 'SQL Error: ' . $error[1]; 
      } 
      return $result; 
     } catch (Exception $exc) { 
      $this->sqlError = 'SQL Error: ' . $exc->getCode(); 
     } 
    } 


} 

回答

1

Catchable Fatal Error也不例外,它是一个错误。它不能被try/catch块捕获,而是被自定义错误处理程序捕获。有关更多信息,请参阅this answer

这条线:

echo $qry; //invalid operation, I expect exception to be thrown 

你是正确的,它是无效的,但不正确的,一个例外是抛出。除非对象具有定义的有效__toString()方法,哪个PDOStatement没有,尝试将其转换为字符串将生成PHP错误,而不是异常。这是因为尝试将对象转换为字符串的代码是PHP内核的一部分,而不是某个类中的某个位。

如果您想查看包含在PDOStatement对象中的查询,您需要访问只读属性$stmt->queryString

+0

'echo $ qry'是故意尝试抛出一个异常,但我现在明白与你的好解释不同。 – andrew