dongping9475 2019-07-30 17:55
浏览 375
已采纳

在函数中捕获异常,在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."

  • 写回答

1条回答 默认 最新

  • dounieqi6959 2019-07-30 18:08
    关注

    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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题