php 用戶自定義異常

<?php
    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);
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章