2016-09-18 73 views
0

我开始学习如何在php中使用异常。在我的代码中的子函数中,如果出现一个错误,我想使用throw语句来停止main函数。php,如何在多重嵌套函数中管理异常?

我有三个功能:

function main_buildt_html(){ 
    ... 
    check_if_parameters_are_ok(); 
    // if the subfunction_check exception is threw, 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页面。

回答

1

通常情况下,这个异常将会一直持续到链条中的最高级别,或者你在任何级别捕获它。

你的情况,如果你想赶上例外check_if_parameters_are_ok()main_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 
    } 
} 

现在你需要赶在main_buildt_html()功能excption。

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

完美!谢谢:) – user2137454

1

check_if_parameters_are_ok()应该返回false当它捕获错误。主要功能应测试该值。

function main_buildt_html(){ 
    ... 
    if (check_if_parameters_are_ok()) { 
     ... 
    } else { 
     ... 
    } 

} 

function check_if_parameters_are_ok(){ 
    ... 
    try{ 
     ... 
     subfunction_check(); 
     ... 
    }catch(Exception $e){ 
     return false; 
    } 
    ... 
} 
+0

谢谢:)但我想传播异常:) – user2137454