为了账号安全,请及时绑定邮箱和手机立即绑定

在函数中捕获异常,在 try-catch 中调用。不起作用,为什么?

在函数中捕获异常,在 try-catch 中调用。不起作用,为什么?

PHP
杨__羊羊 2021-11-05 13:22:07
我试图在 try 块中调用一个函数,如果失败,则捕获异常。我的代码不能正常工作,我做错了什么?对不起,我是例外的新手。有人吗?任何帮助表示赞赏:D我尝试了什么,什么不起作用:function check ($func) {    try {        call_user_func($func);    } catch (Exception $e) {        echo "An error occurred.";    }}function test () {    echo 4/0;}check("test");仅返回“INF”和“被零除”错误,但应捕获该异常并返回“发生错误”。
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

使用 set_exception_handler() 尝试抛出一个不存在的对象将导致 PHP 致命错误。


更多细节 -


1- https://www.php.net/manual/en/language.exceptions.php#language.exceptions.catch


2- https://www.php.net/manual/en/class.errorexception.php


尝试下面的代码,现在错误将被捕获。


   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");


查看完整回答
反对 回复 2021-11-05
  • 1 回答
  • 0 关注
  • 171 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信