php 異常處理機制 例子

來源:互聯網
上載者:User

 

 

從業務的角度講,異常偏重於保護業務資料一致性,並且強調對異常業務的處理。如果代碼種只是象徵性地 try……catch, 然後列印一個錯誤,最後over。這樣的異常不如不用,因為其沒有提想異常思想。

 

<?php//  合理的異常處理:try{    // 可能出錯的程式碼片段    if(出錯判斷1)     throw(異常1);    if(出錯判斷2)     throw(異常2);}catch(異常1){    //必須的補救措施}catch(異常2){    // 補救措施 記錄log}?>

 

 

 

 

<?php// exception 處理例子class emailException extends exception{}class pwdException extends exception{    function __toString(){        return "<div id=\"error\">Exception{$this->getCOde()}:        {$this->getMessage()}        in File:{$this->getFIle()} on line : {$this->getLine()}</div>";    }}function reg($reginfo = null){    // 此處拋出異常的處理順序與後面的try...catch 的順序要相同,不同的話會捕捉不到正確的異常,預設只捕捉到Exception        if(empty($reginfo['email'])){        throw new emailException ('blank email');    }    if($reginfo['pwd'] != $reginfo['repwd']){        throw new pwdException('two pwd is not the same');    }    if(empty($reginfo) || isset($reginfo)){        throw new Exception('error  params');    }    echo 'success';}try{    reg(array('email'=>'aaa@aaa.com', 'pwd'=>'111111', 'repwd'=>'11111'));    //reg();}catch(emailException $ee){    echo $ee->getMessage();}catch(pwdException $ep){    echo $ep;    echo $PHP_EOL,'DIFF DEAL';}catch(Exception $e){    echo $e->getTraceAsString();    echo PHP_EOL, 'other exception , deal the same way';}?>

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.