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();
}
?>

我的结果如下:

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

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

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

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 manual page上有一个简洁的解决方法,将那些“可捕获/可恢复”错误转换为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");
?>

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

<?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();
}
?>
点赞