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.
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.
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.
Error handling in PHP is simple. An error message with filename, line number and a message describing the error is sent to the browser.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With