使用error_reporting()函數設置錯誤級別,代碼示例如下:
<?php // 顯示所有錯誤、警告和提示信息 error_reporting(E_ALL); ?>
<?php // 自定義錯誤處理函數 function customError($errno, $errstr, $errfile, $errline) { echo "<b> Error: [$errno] $errstr - $errfile:$errline"; } // 設置自定義錯誤處理程序set_error_handler("customError"); ?>
通過這種方式,您可以根據錯誤的不同級別和類型執行不同的處理邏輯,比如記錄日誌或發送郵件通知。
<?php // 拋出一個已定義的異常 throw new Exception("Something went wrong."); // 自定義異常類並拋出 class CustomException extends Exception { public function __construct($message, $code = 0, Throwable $previous = null) { parent::__construct($message, $code, $previous); } } throw new CustomException("Custom error occurred."); ?>
<?php try { // 執行可能拋出異常的代碼 throw new Exception("Something went wrong."); } catch (Exception $e) { // 異常處理 echo "Caught exception: " . $e-> getMessage(); } ?>
在catch代碼塊中,您可以通過異常對象的getMessage()方法獲取詳細的異常信息。
<?php try { throw new Exception("Something went wrong."); } catch (CustomException $e) { // 處理自定義異常 echo "Caught custom exception: " . $e-> getMessage(); } catch (Exception $e) { // 處理其他類型的異常echo "Caught exception: " . $e->getMessage(); } ?>
在這段代碼中,如果拋出的是CustomException類型的異常,程序會進入第一個catch代碼塊。如果是其他類型的異常,程序會進入第二個catch代碼塊。