preserveWhiteSpace = false; $container -6ren">
gpt4 book ai didi

PHP 7 try catch : unable to catch "Catchable fatal error"

转载 作者:可可西里 更新时间:2023-10-31 23:37:10 30 4
gpt4 key购买 nike

我正在玩 try - catch block :

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

关于PHP 7 try catch : unable to catch "Catchable fatal error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41774316/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com