try{
echo 'try <br/>';
$mysql = new mysqli('localhost', 'root', '111', 'test');
} catch (Exception $e){
echo 'catch <br/>';
echo $e->getMessage();
}
The code is as above, an exception occurred
Output result:
try
Warning: mysqli::mysqli(): (28000/1045): Access denied for user 'root'@'localhost' (using password: YES) in /home/test/its2/webroot/public/unserialize.php on line 31
Why is the output catch not executed?
PHPz2017-05-16 13:04:45
You need to tell mysqli to throw as an exception instead of a warning.
mysqli_report(MYSQLI_REPORT_STRICT); // 加上这一行!!!
try{
echo 'try <br/>';
$mysql = new mysqli('localhost', 'root', '111', 'test');
} catch (Exception $e){
echo 'catch <br/>';
echo $e->getMessage();
}
Visit again, the results are as follows:
try
catch
Access denied for user 'root'@'localhost' (using password: YES)
阿神2017-05-16 13:04:45
Please clearly distinguish the difference between warning and Exception.
Warning and Error in PHP are PHP's reminders to developers about problems in the program. This problem does not necessarily have to be dealt with.
Exception is a problem that is customized and needs to be dealt with in the application. In principle, there must be a corresponding exception for Exception. Processed