PHP 7尝试 – 捕获:无法捕获“可捕获的致命错误”

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP 7尝试 – 捕获:无法捕获“可捕获的致命错误”脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在玩try – catch块:

<?PHP
try {
    $str = "http://rejstrik-firem.kurzy.cz/73631604";
    $domOb = new DOMDocument();
    $htML = $domOb->loadhtmlFile($str);
    $domOb->PReserveWhITeSpace = false; 
    $container = $domOb->getElementById('ormaininfotab');   
    echo $container; // <========= this is intended error which I want catch
} 
catch (Exception $e) {
   echo "Exception" . $e->getMessage() . ". File: " . $e->getFile() . ",line: " . $e->getLine();
} 

catch (Error $e) {
   echo "Error" . $e->getMessage() . ". File: " . $e->getFile() . ",line: " . $e->getLine();
}
?>

我的结果如下:

为什么第二次捕获没有捕获到这个错误

解决方法

作为 user2782001 mentioned,这不是PHP开发人员眼中的错误.他们甚至指出这些类型的错误应该被称为“可恢复的”:

ErrorException manual page上有一个简洁的解决方法,将那些“可捕获/可恢复”错误转换为ErrorException.

<?PHP
function exception_error_handler($severity,$message,$file,$line) {
    if (!(error_reporting() &amp; $severity)) {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException($message,$severity,$line);
}
set_error_handler("exception_error_handler");
?>

现在,您将能够捕获这些错误

<?PHP
try {
    // Error code
} catch (Error $e) { // this will catch only Errors 
    echo $e->getMessage();
}
?>

要么

try {
    // Error code
} catch (Throwable $t) { // this will catch both Errors and Exceptions
    echo $t->getMessage();
}
?>

脚本宝典总结

以上是脚本宝典为你收集整理的PHP 7尝试 – 捕获:无法捕获“可捕获的致命错误”全部内容,希望文章能够帮你解决PHP 7尝试 – 捕获:无法捕获“可捕获的致命错误”所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。