skip to Main Content

I try to catch exception inside a function, but it is not working.

function dbquery ($mysqli, $query){
  try {
    $result = mysqli_query ($mysqli, $query);
  }
  catch (Exception $e) {
    echo "Caught exception: ".$e->getMessage();                        
    $result = false;
  }
  return $result;
}            

The exception is not caught in the function and an Uncaught mysqli_sql_exception is thrown when the function is called. What am I doing wrong? I dont beleave I have to make a try block around every function call…

2

Answers


  1. You won’t be able to catch all Error could there be with the Exception $e. Try Throwable $e to catch all types of Error.

    For more information, please refer to this question (it’s not PHP question but it’s a similar problem):
    Difference between using Throwable and Exception in a try catch

    Login or Signup to reply.
  2. As far as the official documentation is right the thrown mysqli_sql_exception inherits from RuntimeException and should be catched then, because RuntimeException extends from Exception.

    You could at least try to catch a Throwable in combination with the right mysqli error reporting.

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search