PHP try/catch and fatal error

前端 未结 6 1861
庸人自扰
庸人自扰 2020-12-10 01:01

I\'m using the following script to use a database using PHP:

try{
    $db = new PDO(\'mysql:host=\'.$host.\';port=\'.$port.\';dbname=\'.$db, $user, $pass, $o         


        
6条回答
  •  庸人自扰
    2020-12-10 01:43

    try/catch blocks only work for thrown exceptions (throw Exception or a subclass of Exception must be called). You cannot catch fatal errors using try/catch.

    If your DB connection cannot be established, I would consider it fatal since you probably need your DB to do anything meaningful on the page.

    PDO will throw an exception if the connection cannot be established. Your specific problem is that $db is not defined when you try to call a method with it so you get a null pointer (sort of) which is fatal. Rather than jump through if ($db == null) hoops as others are suggesting, you should just fix your code to make sure that $db is either always defined when you need it or have a less fragile way of making sure a DB connection is available in the code that uses it.

    If you really want to "catch" fatal errors, use set_error_handler, but this still stops script execution on fatal errors.

提交回复
热议问题