我在玩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() & $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尝试-捕获: unable to catch "Catchable fatal error",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41774316/