PHP 7尝试-捕获:无法捕获“可捕获的致命错误"; [英] PHP 7 try - catch: unable to catch "Catchable fatal error"

查看:407
本文介绍了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();
}
?>

我的结果是这样的:

可捕获的致命错误:DOMElement类的对象不能为 在第8行的/var/www/html/cirkve_ares/test.php中转换为字符串

Catchable fatal error: Object of class DOMElement could not be converted to string in /var/www/html/cirkve_ares/test.php on line 8

为什么第二次捕获没有捕获到此错误?

Why is not this error catched by second catch?

推荐答案

As user2782001 mentioned this is not a bug in the eyes of PHP dev's. They even noted that these type of errors should be referenced as 'recoverable':

我们应该摆脱对可捕获的"致命错误(如果它们仍然存在)的任何引用,而应使用可恢复的"致命错误.在这里使用可捕获"令人困惑,因为它们无法使用捕获块来捕获.

we should get rid of any references to "catchable" fatal errors (if they still exist) in favor of "recoverable" fatal errors. Using "catchable" here is confusing as they cannot be caught using catch blocks.

ErrorException手册页上,有一种巧妙的解决方法可以将这些可捕获/可恢复"错误.

On the ErrorException manual page there is a neat workaround converting those "catchable/recoverable" errors to ErrorException.

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

现在您将能够通过以下方式捕获这些错误:

now you will be able to catch those errors with:

<?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尝试-捕获:无法捕获“可捕获的致命错误";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆