亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在函數中捕獲異常,在 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 關注
  • 202 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號