php - 如何管理多个嵌套函数中的异常?

标签 php exception try-catch throw

我正在学习如何在 PHP 中使用异常。在我的代码的子函数中,如果出现错误,我想抛出异常以停止主函数。

我有三个功能:

function main_buildt_html(){
    ...
    check_if_parameters_are_ok();
    // if the subfunction_check exception is thrown, don't execute the process below and go to an error page
    ...
}

function check_if_parameters_are_ok(){
    ...
    try{
        ...
        subfunction_check();
        ...
    }catch(Exception $e){

    }
    ...
}

function subfunction_check(){
    ...
    if ($some_error) throw new Exception("Its not ok ! stop the process and redirect the user to an error page");
    ...
}

从我的主“main_buildt_html”函数中,如何正确检测是否引发了异常?

我想检测主函数中的“子函数”异常,以便我可以停止标准进程并将用户重定向到错误 HTML 页面。

最佳答案

通常,异常会一直抛出,直到链中的最高级别,或者当您在任何级别捕获它时。

在您的情况下,如果您想捕获 check_if_parameters_are_ok()ma​​in_buildt_html() 函数中的异常,则需要在 check_if_parameters_are_ok() 函数。

function check_if_parameters_are_ok(){
    ...
    try{
        ...
        subfunction_check();
        ...
    }catch(Exception $e){
     //handle exception. 
     throw $e; // throw the excption again
    }
}

现在您需要捕获 ma​​in_buildt_html() 函数中的表达式。

function main_buildt_html(){
    try {
        check_if_parameters_are_ok();
    } catch (Exception $e) {
        // handle the excption
    }   
}

关于php - 如何管理多个嵌套函数中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555470/

相关文章:

javascript - Div 重新加载 jquery 并用它传递 PHP 变量

c# - 异常记录和发送电子邮件

python - Python中的自定义异常似乎不遵循 "its easier to ask for forgiveness"?

python - 使用 try/catch 重试相同的方法

c# - 嵌套尝试/捕捉

PHP MYSQL > 搜索用户名并回显列数据

php - INNER JOIN 后表中的字段未正确显示 - undefined index

php - 检查php中的链接是否损坏

mysql - 为什么与mysql交互时跳出while循环?

java - 用 if 条件替换 try-catch block