1<?PHP2 /*3 Exception4 5 */6 //error_reporting (0);7 class Mysql {8 protected $conn;9 Public function__construct () {Ten $this->conn = @mysql_connect(' localhost ', ' root ', ' 13456 ');//@ is an error suppressor and does not report an error One if(!$this-conn) { A //Satellite Reports - //In PHP, a satellite is a defined object - ///What Class of object: Exception class object the //new Exception (' Error reason ', error code) - $e=New Exception(' Leaking oil ', 5); - Throw $e;//Throw throw /throw out - } + } - } + Try{//Test and try to capture the error message A $mysql=New Mysql();//returns the MySQL object and automatically connects to the database at - -}Catch(Exception $e) { - Echo $e, ' <br/> '; - Echo' Capture to error message <br/> '; - Echo' Error message: ',$e->getmessage (), ' <br/> '; in Echo' Error code: ',$e->getcode (), ' <br/> '; - Echo' Error file: ',$e->getfile (), ' <br/> '; to Echo' ERROR line: ',$e->getline (), ' <br/> '; + } - the /* * Q: How can I tell if I have successfully connected to the database? $ Answer: After returning an object, print the object's $conn property to determinePanax Notoginseng - 2 Steps Required the 1:new Mysql + 2:if ($mysql->conn) { A } the think: When we used a function, we all returned a value, using the value to judge a variety of situations + For example, returning True/false represents success/Failure - Can we use the return value now? $ $ */ - Var_dump($mysql);//NULL if the database connection failed - if($mysqlinstanceofMysql) { the Echo' Create object successfully, probably connected successfully '; -}Else {Wuyi Echo' Failed to create object, probably connection failed '; the } -?>
Exception Handling of PHP