當前位置:學者齋 >

計算機 >php語言 >

PHP7的異常處理詳解

PHP7的異常處理詳解

在PHP中碰到異常的時候應該如何處理呢,就跟隨本站小編一起去了解下吧,想了解更多相關信息請持續關注我們應屆畢業生考試網!

PHP7的異常處理詳解

前言

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/ on line 14" ["string":"Error":private]=> string(0) "" ["code":protected]=> int(0) ["file":protected]=> string(48) "/Applications/mamp/apache2/htdocs/curl/" ["line":protected]=> int(9) ["trace":"Error":private]=> array(1) { [0]=> array(4) { ["file"]=> string(48) "/Applications/mamp/apache2/htdocs/curl/" ["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
  • 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-hk/jsj/php/o6lg0z.html