- 相關推薦
PHP7的異常處理詳解
在PHP中碰到異常的時候應該如何處理呢,就跟隨百分網小編一起去了解下吧,想了解更多相關信息請持續關注我們應屆畢業生考試網!
前言
PHP7的改動中,影響比較大的,包括異常處理。
概述
更多的異常是直接通過PHP直接處理的,和之前的PHP5不同的是更多的異常是通過Error exceptions來拋出。
作為一個普通的擴展,Error exceptions會持續冒出直到匹配到對應的catch塊。如果沒有進行匹配,就會觸發被設置的set_exception_handler()來執行處理,如果沒有默認的異常處理程序,則該異常將被轉換為一個致命錯誤,并且將被像一個傳統的錯誤被處理。
由于Error在錯誤層次結構不繼承異常,像這樣的代碼catch (Exception $e) { ... }在PHP5中并不會捕獲到對應的異常。我們可以用代碼catch (Error $e) { ... }或者 set_exception_handler(),來對Error進行處理。
錯誤的層級結構
Throwable
Error 錯誤
ArithmeticError 算數錯誤
PisionByZeroError 除數為0的錯誤
AssertionError 聲明錯誤
ParseError 解析錯誤
TypeError 類型錯誤
Exception 異常
….
PHP RFC
Throwable Interface
function add(int $left, int $right) { return $left + $right;}try { echo add('left', 'right');} catch (Exception $e) { // Handle exception} catch (Error $e) { // Clearly a different type of object // Log error and end gracefully var_dump($e);}
這里,并沒有出現服務器500的錯誤。原因在于,PHP7中的Error把它攔截住了,沒有冒泡在服務器中。
object(TypeError)#1 (7) { ["message":protected]=> string(139) "Argument 1 passed to add() must be of the type integer, string given, called in /Applications/mamp/apache2/htdocs/curl/error.php on line 14" ["string":"Error":private]=> string(0) "" ["code":protected]=> int(0) ["file":protected]=> string(48) "/Applications/mamp/apache2/htdocs/curl/error.php" ["line":protected]=> int(9) ["trace":"Error":private]=> array(1) { [0]=> array(4) { ["file"]=> string(48) "/Applications/mamp/apache2/htdocs/curl/error.php" ["line"]=> int(14) ["function"]=> string(3) "add" ["args"]=> array(2) { [0]=> string(4) "left" [1]=> string(5) "right" } } } ["previous":"Error":private]=> NULL}
這樣我們就可以通過日志的方式記錄他們。
Exceptions in the engine (for PHP 7)
function call_method($obj) { $obj->method();}try { call_method(null); // oops!} catch (EngineException $e) { echo "Exception: {$e->getMessage()}/n";}//其實上面的例子我在運行過程中,并沒有被EngineException捕獲異常,經過測試,也是通過Error進行的錯誤的攔截
如果異常沒有被捕獲,PHP將繼續擔任目前它拋出同樣的致命錯誤。
【PHP7的異常處理詳解】相關文章:
PHP7系列中的異常處理08-11
PHP7系列之-異常處理06-07
Java編程中異常處理的方法10-02
全面理解java中的異常處理機制精選08-11
PHP5異常處理的方法是什么09-01
交通事故處理流程詳解07-12
Linux中生成Core Dump系統異常信息記錄文件處理方法介紹08-17
十件在PHP7中不要做的事情10-15
PHP7的五大新特性有哪些08-11
Dreamweaver技巧詳解09-01