search

Home  >  Q&A  >  body text

php exception handling

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?

大家讲道理大家讲道理2834 days ago500

reply all(3)I'll reply

  • PHPz

    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)

    reply
    0
  • 阿神

    阿神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

    reply
    0
  • 黄舟

    黄舟2017-05-16 13:04:45

    Look at this http://www.cnblogs.com/water0...

    reply
    0
  • Cancelreply