使用 error_reporting() 函数设置错误级别,代码示例如下:
<?php // 显示所有错误、警告和提示信息 error_reporting(E_ALL); ?>
<?php // 自定义错误处理函数 function customError($errno, $errstr, $errfile, $errline) { echo "<b>Error:</b> [$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 代码块。