我读到,当在类方法中抛出异常时,执行会停止,并且异常会在调用堆栈中冒泡,寻找相同异常类型的立即捕获 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/