Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try-catch not working

try     
{
    $matrix = Query::take("SELECT moo"); //this makes 0 sense

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

    }

    return 'something';
}
catch(Exception $e)
{
    return 'nothing';   
}

However instead of just going to catch part and returning nothing it shows a warning Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in the line starting with while. I have never came up to using exceptions in php, but used them a lot in C# and it seems in PHP they are working differently or, as always, I am missing something obvious.

like image 417
Andrius Naruševičius Avatar asked Sep 11 '12 20:09

Andrius Naruševičius


People also ask

Does try catch stop execution PHP?

Try catch in PHP is a block that contains the program's vital code for execution. In PHP, the finally block is also used to clean up the code. The only difference is that it always runs regardless of whether or not an exception is thrown.

How can I get fatal error in PHP?

You can "catch" these "fatal" errors by using set_error_handler() and checking for E_RECOVERABLE_ERROR. I find it useful to throw an Exception when this error is caught, then you can use try/catch.

What is PHP error handling?

Error handling in PHP is simple. An error message with filename, line number and a message describing the error is sent to the browser.


3 Answers

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.

like image 79
Philipp Avatar answered Oct 17 '22 07:10

Philipp


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.

like image 33
Gilad Tiram Avatar answered Oct 17 '22 09:10

Gilad Tiram


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.

like image 6
datasage Avatar answered Oct 17 '22 09:10

datasage