How do I raise PDOException?

前端 未结 2 1088
执笔经年
执笔经年 2021-01-03 05:08

This code works fine, but I\'ll want to handle exception if any thing goes wrong, so I deliberately made a syntax error in the query but nothing ha

相关标签:
2条回答
  • 2021-01-03 05:25

    Exceptions are thrown. Syntax errors in code != Exceptions.

    <?php 
        try {
            $code = 12;
            throw new PDOException('Message', $code );
        } catch (PDOException $e) {
    
        }
    ?>
    

    However, from the maual:

    You should not throw a PDOException from your own code. See Exceptions for more information about Exceptions in PHP.

    My advice is to throw either a general exception, or to write your own custom exception to handle your error.

    0 讨论(0)
  • 2021-01-03 05:30

    Be sure to set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, as soon as you init your pdo object:

    $lecturers_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    

    After that, any failed queries will raise an exception

    0 讨论(0)
提交回复
热议问题