PHP异常冒泡混乱
我了解到,当在类方法中抛出异常时,执行停止,异常在调用堆栈中冒泡,寻找相同异常类型的立即捕获块 以下面的代码为例PHP异常冒泡混乱,php,exception,Php,Exception,我了解到,当在类方法中抛出异常时,执行停止,异常在调用堆栈中冒泡,寻找相同异常类型的立即捕获块 以下面的代码为例 class Foo { public function methodOne() { $this->methodTwo(); // more code } public function methodTwo() { try { $this->methodThr
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
中下移以继续,而methodtwree
中的异常会中断执行
或者换句话说,在捕获异常后,它是否保留了调用堆栈?我获取了您的代码并添加了回溯打印和代码执行,以便您可以看到发生了什么 您的问题的答案是,程序继续在try-catch块的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]
#0foo->methodThree()在[/php\u playerd/index.php:25]调用
#1 Foo->methodTwo()在[/php\u playerd/index.php:16]调用
#2 Foo->methodOne()在[/php\u playway/index.php:46]调用
方法二发现错误
#0 Foo->methodTwo()在[/php\u playway/index.php:16]调用
#1 Foo->methodOne()在[/php\u playway/index.php:46]调用
方法二继续执行
#0 Foo->methodTwo()在[/php\u playway/index.php:16]调用
#1 Foo->methodOne()在[/php\u playway/index.php:46]调用
方法一继续执行
#0 Foo->methodOne()在[/php\u playway/index.php:46]处调用
所以,您的问题的答案是,程序在try-catch块的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');
}
}
class-Foo
{
公共功能方法一()
{
$this->methodTwo();
echo“methodOne继续执行””;
调试打印回溯();
回声“
”;
}
公共功能方法二()
{
试一试{
$this->methodThree();
}捕获(例外$e){
echo“methodTwo捕获错误””;
调试打印回溯();
回声“
”;
}
echo“方法二继续执行””;
调试打印回溯();
回声“
”;
}
公共职能方法三
{
调试打印回溯();
回声“
”;
抛出新异常(“异常发生”);
}
}
您是否使用var\u dump
或echo
测试异常抛出的不同变体?很明显,捕捉到异常后,php将继续处理catch块、finally块以及try-catch最终保留堆栈调用后的其余代码。