php,如何管理多个嵌套函数中的抛出异常?
php, how manage throw exception in multiple nested function?
我开始学习如何在 php 中使用异常。在我的代码的一个子函数中,如果出现一个错误,我想使用一个 throw 语句来停止主函数。
我有三个功能:
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" 函数中,如果抛出异常,我如何正确 'detect' ?
我想检测 "subfunction" 主函数的异常以停止标准进程并将用户重定向到错误 html 页面。
通常情况下,异常会一直抛出到链中的最高级别,或者当您在任何级别捕获它时。
在你的情况下,如果你想捕获 check_if_parameters_are_ok() 和 main_buildt_html()[=22 中的异常=]函数,需要在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
}
}
check_if_parameters_are_ok()
在发现错误时应该 return 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;
}
...
}
我开始学习如何在 php 中使用异常。在我的代码的一个子函数中,如果出现一个错误,我想使用一个 throw 语句来停止主函数。
我有三个功能:
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" 函数中,如果抛出异常,我如何正确 'detect' ?
我想检测 "subfunction" 主函数的异常以停止标准进程并将用户重定向到错误 html 页面。
通常情况下,异常会一直抛出到链中的最高级别,或者当您在任何级别捕获它时。
在你的情况下,如果你想捕获 check_if_parameters_are_ok() 和 main_buildt_html()[=22 中的异常=]函数,需要在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
}
}
check_if_parameters_are_ok()
在发现错误时应该 return 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;
}
...
}