我正在学习如何在PHP中使用异常。在我代码的子函数中,如果出现错误,我想抛出一个Exception来停止主函数。
我有三个功能:
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");
...
}
From my main "main_buildt_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
}
}
check_if_parameters_are_ok()
捕获错误时应返回false
。main函数应该测试这个值
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;
}
...
}