PHP 異常與錯誤 筆記與總結(17 )像處理錯誤一樣處理 PHP 異常

來源:互聯網
上載者:User
PHP 錯誤與異常 筆記與總結(17 )像處理異常一樣處理 PHP 錯誤

有兩種方式可以在 PHP 中以異常的方式處理錯誤:

① PHP 內建的 ErrorException 類(也是 Exception 類的子類)

 1 php 2 function exception_error_handler($errno, $errstr, $errfile, $errline){ 3     throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 4 } 5  6 set_error_handler('exception_error_handler'); 7  8 try{ 9     //出發異常10     echo gettype();11 }catch(Exception $e){12     echo $e->getMessage();13 }

輸出:

用過這種方式把警告資訊以異常資訊輸出出來了。

② 自訂異常類來處理 PHP 中的錯誤

 1 php 2 class ErrorToException extends Exception{ 3     public static function handler($errno, $errstr){ 4         throw new self($errstr, $errno); 5     } 6 } 7  8 set_error_handler(array('ErrorToException', 'handler')); 9 10 try{11     //觸發錯誤,未定義的變數,產生通知層級的錯誤12     echo $test;13 }catch(ErrorToException $e){14     echo $e->getMessage();15 }

輸出:

還可以使用 set_error_handler 設定錯誤層級:

 1 php 2 class ErrorToException extends Exception{ 3     public static function handler($errno, $errstr){ 4         throw new self($errstr, $errno); 5     } 6 } 7  8 set_error_handler(array('ErrorToException', 'handler')); 9 //設定錯誤層級,例如只有警告層級的錯誤才以異常的形式進行捕獲10 set_error_handler(array('ErrorToException', 'handler'), E_USER_WARNING|E_WARNING);11 12 try{13     //觸發錯誤,未定義的變數,產生通知層級的錯誤14     echo $test;15 }catch(ErrorToException $e){16     echo $e->getMessage();17 }

輸出:

也就是說,通知層級的錯誤不交給自訂異常類來處理。

trigger_error 也能觸發異常:

 1 php 2 header('content-type:text/html; charset=utf-8'); 3  4 class ErrorToException extends Exception{ 5     public static function handler($errno, $errstr){ 6         throw new self($errstr, $errno); 7     } 8 } 9 10 set_error_handler(array('ErrorToException', 'handler'));11 //設定錯誤層級,例如至喲喲警告層級的錯誤才以異常的形式進行捕獲12 set_error_handler(array('ErrorToException', 'handler'), E_USER_WARNING|E_WARNING);13 14 try{15     //觸發錯誤,未定義的變數,產生通知層級的錯誤16     echo $test;17     echo '';18     //gettype();19     echo '';20     trigger_error('test', E_USER_WARNING);21 }catch(ErrorToException $e){22     echo '異常';23     echo $e->getMessage();24 }

輸出:

  • 聯繫我們

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