在函数中捕获异常,在try-catch中调用。 不起作用,为什么?
I'm trying to call a function inside try block and if it fails, catch an exception. My code doesn't work right, what am I doing wrong? Sorry, I'm new on exceptions. Anybody? Any help appreciated :D
What I tried and what doesn't works:
function check ($func) {
try {
call_user_func($func);
} catch (Exception $e) {
echo "An error occurred.";
}
}
function test () {
echo 4/0;
}
check("test");
Returns just "INF" and "Division by zero" error, but should catch that exception and return "An error occurred."
我正在尝试调用try块中的函数,如果失败,则捕获异常。 我的代码不正常,我做错了什么? 对不起,我是新的例外。 任何人? 任何帮助表示赞赏:D p>
我尝试了什么,什么不起作用: p>
函数检查($ func){
尝试{
call_user_func($ func);
} catch(异常$ e){
echo“发生错误。”;
}
}
函数测试 (){
echo 4/0;
}
check(“test”);
code> pre>
返回“INF”和“除以零” “错误,但应该捕获该异常并返回”发生错误。“ p>
div>
Trying to throw an object that is not will result in a PHP Fatal Error using set_exception_handler().
For more details -
1- https://www.php.net/manual/en/language.exceptions.php#language.exceptions.catch
2- https://www.php.net/manual/en/class.errorexception.php
Try the below code, now error will go to catch.
function exception_error_handler($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting
return;
}
if($message == 'Division by zero'){
throw new DivisionByZeroError('Division By Zero Error');
}else{
throw new ErrorException($message, 0, $severity, $file, $line);
}
}
set_error_handler("exception_error_handler");
function check ($func) {
try {
call_user_func($func);
}
catch (DivisionByZeroError $e) {
echo "An Division error occurred - ".$e->getMessage(); //$e->getMessage() will deisplay the error message
}
catch (Exception $e) {
echo "An error occurred - ".$e->getMessage(); //$e->getMessage() will deisplay the error message
}
}
function test () {
echo 4/0;
}
check("test");