PHP异常冒泡困惑

标签 php exception

我读到,当在类方法中抛出异常时,执行会停止,并且异常会在调用堆栈中冒泡,寻找相同异常类型的立即捕获 block 。

以下面的代码为例。

class Foo
{

    public function methodOne()
    {
        $this->methodTwo();
        // more code
    }

    public function methodTwo()
    {
        try {
            $this->methodThree();
        } catch (Exception $e) {

        }
    }

    public function methodThree()
    {
        throw new Exception('exception happened');
    }

}

$foo = new Foo();
$foo->methodOne();

我的问题是,当调用堆栈捕获到异常时,执行会从哪里重新开始? 例如上面的例子,在methodTwo中捕获了异常,执行是否会向下移动到methodOne中继续执行,而在methodThree中被异常中断?

或者说异常被捕获后,是否保留了调用栈?

最佳答案

我获取了您的代码并添加了回溯打印和代码执行,这样您就可以看到发生了什么。

您的问题的答案是程序继续执行 try catch block 的 catch 部分,并在完成错误时继续执行它之后的代码。

它看起来与此类似(我改进了原始格式)。您可以查看下面的示例。

#0  Foo->methodThree() called at [/php_playground/index.php:25] <br> 
#1 Foo->methodTwo() called at [/php_playground/index.php:16] <br>
#2 Foo->methodOne() called at [/php_playground/index.php:46] <hr>

methodTwo caught error
#0  Foo->methodTwo() called at [/php_playground/index.php:16] <br>
#1  Foo->methodOne() called at[/php_playground/index.php:46] <hr> 

methodTwo continuing execution
#0  Foo->methodTwo() called at [/php_playground/index.php:16] <br>
#1  Foo->methodOne() called at [/php_playground/index.php:46] <hr> 

methodOne continuing execution
#0  Foo->methodOne() called at [/php_playground/index.php:46]

所以你的问题的答案是程序在 try catch block 的 catch 部分继续执行,并在完成错误时继续执行它之后的代码。

这是我用于此打印的代码,因此您可以自己玩一下。

class Foo
{

    public function methodOne()
    {
        $this->methodTwo();
        echo "<p>methodOne continuing execution</p>";
        debug_print_backtrace();
        echo "<hr>";
    }

    public function methodTwo()
    {
        try {
            $this->methodThree();
        } catch (Exception $e) {
            echo "<p>methodTwo caught error</p>";
            debug_print_backtrace();
            echo "<hr>";
        }

        echo "<p>methodTwo continuing execution</p>";
        debug_print_backtrace();
        echo "<hr>";
    }

    public function methodThree()
    {
        debug_print_backtrace();
        echo "<hr>";
        throw new Exception('exception happened');
    }
}

关于PHP异常冒泡困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656641/

相关文章:

php - Zend_Session_SaveHandler_DbTable 是否在每次刷新时删除 session ?

JavaScript 值到另一个 PHP 页面

php - Symfony 4 Custom Bundle 使用 Logger Interface

python - 处理轨迹奇点: delete photons causing error

android - 如何在 Fragment 中创建一个 MapView

php - shop_item_id 必须有效

php - 有没有办法将 Python 中的字典提取到本地 namespace 中?

c++ - C++ 异常和结构化异常之间的区别

mysql - 引发 MysqlError; raise Mysql::Error 都有效,这是怎么发生的?

c 抛出异常 : read access violation. srv 为 nullptr