PHP try-catch not working

后端 未结 5 560
慢半拍i
慢半拍i 2020-12-16 10:51
try     
{
    $matrix = Query::take(\"SELECT moo\"); //this makes 0 sense

    while($row = mysqli_fetch_array($matrix, MYSQL_BOTH)) //and thus this line should be          


        
相关标签:
5条回答
  • 2020-12-16 11:24

    Exception is only subclass of Throwable. To catch error you can try to do one of the following:

    try {
    
        catch (\Exception $e) {
           //do something when exception is thrown
    }
    catch (\Error $e) {
      //do something when error is thrown
    }
    

    OR more inclusive solution

    try {
    
    catch (\Exception $e) {
       //do something when exception is thrown
    }
    catch (\Throwable $e) {
      //do something when Throwable is thrown
    }
    

    BTW : Java has similar behaviour.

    0 讨论(0)
  • 2020-12-16 11:24

    PHP is generating a warning, not an exception. Warnings can't be caught. They are more like compiler warnings in C#.

    0 讨论(0)
  • 2020-12-16 11:28

    You can't handle Warnings/Errors with try-catch blocks, because they aren't exceptions. If you want to handle warnings/errors, you have to register your own error handler with set_error_handler.

    But it's better to fix this issue, because you could prevent it.

    0 讨论(0)
  • 2020-12-16 11:46

    In PHP a warning is not an exception. Generally the best practice would be to use defensive coding to make sure the result is what you expect it to be.

    0 讨论(0)
  • 2020-12-16 11:47

    Welp, unfortunately this is the issue about PHP. Try/catch statements will catch Exceptions, but what you're receiving is an old-school PHP error.

    You'll have to catch an error like this with: http://php.net/manual/en/function.set-error-handler.php

    Either that or check to see if $matrix is a mysqli_result object prior to performing mysqli_fetch_array.

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