前言
PHP7的改變中,影響比較大的,包括異常處理。
概述
更多的異常是直接透過PHP直接處理的,和之前的PHP5不同的是更多的異常是透過Error exceptions來拋出。
作為一個普通的擴展,Error exceptions會持續冒出直到匹配到對應的catch
區塊。如果沒有進行匹配,就會觸發被設定的set_exception_handler()
來執行處理,如果沒有預設的異常處理程序,則該異常將被轉換為一個致命錯誤,並且將被像一個傳統的錯誤被處理。
由於Error在錯誤層次結構中不繼承異常,像這樣的程式碼catch (Exception $e) { ... }
在PHP5中並不會捕獲到對應的例外。我們可以用程式碼catch (Error $e) { ... }
或 set_exception_handler()
,來處理Error。
錯誤的層級結構
Throwable
#….
-
ArithmeticError 算數錯誤
#AssertionError 宣告錯誤
##ParseError 解析錯誤
-
ParseError 解析錯誤
#TypeError 類型錯誤
pisionByZeroError 除數為0的錯誤
##Error 錯誤
#Exception 例外
######PHP RFC######Throwable Interface###
1 2 3 4 5 6 7 | function add(int $left , int $right ) {
return $left + $right ;
} try { echo add('left', 'right');
} catch (Exception $e ) {
var_dump( $e );
}
|
登入後複製
###這裡,並沒有出現伺服器500的錯誤。原因在於,PHP7中的Error把它攔截住了,沒有冒泡在伺服器中。 ###
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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)###
1 2 3 4 5 6 7 8 9 | function call_method( $obj ) {
$obj ->method();
} try {
call_method(null);
}
catch (EngineException $e ) {
echo "Exception: { $e ->getMessage()}\n";
}
|
登入後複製
###如果例外沒有被捕獲,PHP將繼續擔任目前它拋出同樣的致命錯誤。 ######Reclassify E_STRICT notices############
以上是詳細介紹PHP7的異常處理程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!