And*_*ius 18 php exception try-catch
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';
}
Run Code Online (Sandbox Code Playgroud)
然而,而不是只是去捕捉部分并返回nothing
它显示Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given
在行开始时的警告while
.我从来没有在php中使用异常,但在C#中使用它们很多,而且在PHP中看起来它们的工作方式不同,或者像往常一样,我遗漏了一些明显的东西.
Phi*_*ipp 31
您无法使用try-catch块处理警告/错误,因为它们不是例外.如果要处理警告/错误,则必须注册自己的错误处理程序set_error_handler
.
但最好解决这个问题,因为你可以阻止它.
异常只是Throwable的子类。要捕获错误,您可以尝试执行以下操作之一:
try {
catch (\Exception $e) {
//do something when exception is thrown
}
catch (\Error $e) {
//do something when error is thrown
}
Run Code Online (Sandbox Code Playgroud)
或更广泛的解决方案
try {
catch (\Exception $e) {
//do something when exception is thrown
}
catch (\Throwable $e) {
//do something when Throwable is thrown
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句:Java具有类似的行为。