php 使用者自訂異常

來源:互聯網
上載者:User

    class ZeroDivisorException extends Exception{
        public function __construct(){
            parent::__construct('被0除異常', 101);
        }

        public function __toString(){
            $msg = $this->getMessage();
            $code = $this->getCode();
            $file = $this->getFile();
            $line = $this->getLine();

            $ret = "/n-------------------------------------/n";
            $ret .= "有錯誤發生!/n";
            $ret .= "錯誤號碼: $code/n";
            $ret .= "錯誤訊息: $msg /n";
            $ret .= "檔案: $file/n";
            $ret .= "行號: $line/n";
            $ret .= "-------------------------------------/n/n";

            return $ret;
        }
    }

    class NotExactDivisionException extends Exception{
        private    $_integer;
        private $_fraction;

        public function __construct($integer, $fraction){
            parent::__construct('不能整除異常', 102);
            $this->_integer = $integer;
            $this->_fraction = $fraction;
        }

        public function getInteger(){
            return $this->_integer;
        }

        public function getFraction(){
            return $this->_fraction;
        }
    }

    function div($dividend, $divisor){
        try{
            echo "$dividend 除以$divisor  -> /n";
            if(0 == $divisor){
                throw new ZeroDivisorException();
            }
            else if($dividend % $divisor != 0){
                $integer = (int)($dividend / $divisor);
                $fraction = $dividend % $divisor;
                throw new NotExactDivisionException($integer, $fraction);
            }

            $result = $dividend / $divisor;
            echo "結果為 $result/n/n";
        }

        catch(NotExactDivisionException $e){  #下面不能為"結果為:$e->getInteger(), 餘數為$e->getFraction()/n/n";
            echo "結果為:".$e->getInteger().", 餘數為 ".$e->getFraction()."/n/n";
        }

        catch(ZeroDivisorException $e){
            echo $e;
        }

        catch(Exception $e){ #通常應該把捕獲 Exception 類型異常的 catch 塊放在最後,以捕獲任何其它異常
            echo $e;
        }
    }

    div(100, 10);
    div(100, 0);
    div(100, 30);
?>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.