與以前的版本相比,如何處理PHP 7中的異常? 核心機構仍然是
塊。 多個try...catch
塊可用於處理不同的異常類型。 最後,無論是拋出還是被捕獲,可選的try
塊執行。 catch
>catch
這是一個基本示例。 finally
塊捕獲此異常,顯示錯誤消息,而
catch-all。
try { // Code that might throw an exception $file = fopen("nonexistent.txt", "r"); if ($file === false) { throw new Exception("Could not open file."); } fclose($file); } catch (Exception $e) { // Handle the exception echo "An error occurred: " . $e->getMessage(); } finally { // Code that always executes echo "\nThis always runs."; }
catch (Exception $e)
finally
>清理>中的資源:finally
使用try
> block以在Exception
>如何在PHP 7中創建自定義異常,以進行更好的錯誤管理?
try { // Code that might throw an exception $file = fopen("nonexistent.txt", "r"); if ($file === false) { throw new Exception("Could not open file."); } fclose($file); } catch (Exception $e) { // Handle the exception echo "An error occurred: " . $e->getMessage(); } finally { // Code that always executes echo "\nThis always runs."; }
MyCustomException
data
>來創建自定義,此示例定義了
> php 7和更早版本之間的異常處理的差異有何不同?
PHP 7給異常提供了一些改進:PHP 7中的set_exception_handler()
No more reliance for all exceptions:set_exception_handler()
While 以上是如何處理PHP 7中的例外?的詳細內容。更多資訊請關注PHP中文網其他相關文章!