是否可以判断我们是否在外部 try..catch 块内?
示例代码(请仅作为示例):
<?php
class Foo{
public function load($id)
{
try{
// Model throw NodeNotFoundException only in rare cases
$node = $this->getModel()->loadById($id);
}
catch(NodeNotFoundException $nle)
{
// @here I need to tell if im in the First case or in the Second one,
// detecting the external try..catch block
if(externalTryCatchBlock() === true)
{
throw $nle;
}
else
{
watchdog('Unable to find node', $nle->details);
}
return false;
}
catch(Exception $e)
{
watchdog('Something gone wrong.');
return null;
}
return $node;
}
}
$foo = new Foo();
// First case, no external try..catch
$node = $foo->load(2);
// Second case: we need to do here something different if the node load
// throw an exception
try{
$another_node = $foo->load(3);
}
catch(NodeNotFoundException $nle)
{
watchdog('Unable to find node, using default.');
$another_node = Bar::defaultNode(); // This is JUST for example
}
// Do something with $another_node
?>
NodeNotFoundException
基本上,只有当有另一个 catch 块等待它时,我才需要重新抛出异常 ( ),以避免Fatal error: Uncaught exception
.
当然,对于上面的示例,我可以使用 2 种加载方法(一种使用 try..catch,另一种不使用 try..catch),但我想避免这种情况。我很想知道是否可以检测到 try。 PHP 中的 .catch 块