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

我试图在 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”和“被零除”错误,但应捕获该异常并返回“发生错误”。


杨__羊羊
浏览 176回答 1
1回答

一只名叫tom的猫

使用 set_exception_handler() 尝试抛出一个不存在的对象将导致 PHP 致命错误。更多细节 -1- https://www.php.net/manual/en/language.exceptions.php#language.exceptions.catch2- 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");
打开App,查看更多内容
随时随地看视频慕课网APP