【问题标题】:PHP: detect if we are inside an outer try..catch blockPHP:检测我们是否在外部 try..catch 块内
【发布时间】:2013-03-13 14:00:50
【问题描述】:

是否可以判断我们是否在外部 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
?>

基本上,只有在有另一个 catch 块等待它时,我才需要重新抛出异常 (NodeNotFoundException),以避免 Fatal error: Uncaught exception

当然,对于上面的示例,我可以使用 2 种加载方法(一种带有 try..catch,另一种不带 try..catch),但我想避免这种情况。我很想知道是否有可能检测 PHP 中的 try..catch 块

【问题讨论】:

    标签: php exception exception-handling try-catch


    【解决方案1】:

    担心如何调用它不是一段代码的工作。代码总是抛出异常,故事结束。因此代码具有“属性”可能会抛出异常x

    /**
     * Does something.
     *
     * @return mixed Some value.
     * @throws SomeException if something went wrong.
     */
    function foo() {
       ...
    }
    

    现在,调用此代码的任何人都需要做好随时抛出异常的准备。代码不必担心是否有人可以捕获异常。如果出现异常情况,它会抛出异常,因为它无法继续完成其工作。 调用者需要为此做好准备,而不是相反。

    【讨论】:

    • 正如我之前所说,这只是一个例子,也是我脑海中浮现的一种好奇心。顺便说一句,我们可能会遇到不同类型的异常情况——对于上面的示例,如果找不到节点是错误的,但如果节点是另一个实体的字段,假装该节点存在,我们必须做其他事情。
    • 话虽如此,我不知道是否有一种理智的编程方式来确定您是否在try..catch 块中,但我不认为存在是。由于上述原因,拥有这样的东西听起来是个坏主意,而我从未听说过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2011-06-08
    • 2016-02-01
    相关资源
    最近更新 更多