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

我正在玩try – catch块:

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.

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");

?>

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

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

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值