我正在学习如何在 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() 和 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() 函数中的表达式。
function main_buildt_html(){
try {
check_if_parameters_are_ok();
} catch (Exception $e) {
// handle the excption
}
}
关于php - 如何管理多个嵌套函数中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555470/