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';
}
但是,它不是仅仅捕获部分并返回nothing,而是在以while开头的行中显示警告Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given。 我从来没有在php中使用异常,但在C#中使用它们很多,而且在PHP中看起来它们的工作方式不同,或者像往常一样,我遗漏了一些明显的东西。
以下是您的问题:stackoverflow.com/questions/1241728/can-i-try-catch-a-warning
重复:stackoverflow.com/questions/1241728/can-i-try-catch-a-warning
阅读此phpmaster.com/error-handling-in-php
@SirDarius - 有趣且有价值的阅读链接。 谢谢 :)
您无法使用try-catch块处理警告/错误,因为它们不是例外。如果要处理警告/错误,则必须使用set_error_handler注册自己的错误处理程序。
但最好解决这个问题,因为你可以阻止它。
在这个答案的基础上,您可以轻松设置set_error_handler来捕获PHP错误并发出异常,此时您的try-catch将起作用。 我相信你可以通过谷歌获得合适的东西。
对于抛出异常,set_error_handler应与ErrorException(专门用于此用途的内置类)结合使用。
我已经做了几年PHP的全职工作,我甚至都不知道这一点。
在PHP中,警告不是例外。通常,最好的做法是使用防御性编码来确保结果符合您的预期。
异常只是Throwable的子类。要捕获错误,您可以尝试执行以下操作之一:
try {
catch (\Exception $e) {
//do something when exception is thrown
}
catch (\Error $e) {
//do something when error is thrown
}
或者包容性更强
try {
catch (\Exception $e) {
//do something when exception is thrown
}
catch (\Throwable $e) {
//do something when Throwable is thrown
}
BTW:Java有类似的行为。
Welp,遗憾的是这是关于PHP的问题。 Try / catch语句将捕获异常,但您收到的是一个老派的PHP错误。
你必须得到这样的错误:
http://php.net/manual/en/function.set-error-handler.php
或者在执行mysqli_fetch_array之前检查$ matrix是否是mysqli_result对象。
老式的PHP错误处理对我有用。 感谢您指点我正确的方向!
PHP正在生成警告,而不是例外。警告无法捕获。它们更像是C#中的编译器警告。