php错误处理。捕获另一个尝试捕获引发的异常

问题描述 投票:0回答:1

我可以这样做吗?为什么它不起作用,如果不可能的话,还有另一种方法可以在不更改sth()代码的情况下做类似的事情吗?

function sth(){
   try {
       sth_else();
   } catch (Exception $e) {
        throw new AnotherException('fubar');
   }
}

try {
    sth();
} catch (AnotherException $e) {
    //pass
}
php
1个回答
0
投票
<?php
class AnotherException extends Exception{}

function foo() {
    throw new Exception('fubar');
}

function bar() {
    try {
        foo();
    } catch (Exception $e) {
        throw new AnotherException($e->getMessage());
    }
}

try {
    call_user_func('bar');
} catch (AnotherException $e) {
    echo $e->getMessage();
}

只是写了一个测试,它确实起作用了……我很困惑。

© www.soinside.com 2019 - 2024. All rights reserved.