Home >Backend Development >PHP Tutorial >Extending PHP's exception handling class_PHP tutorial
PHP 5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Every try must have at least one corresponding catch. Use multiple catches to catch exceptions generated by different classes. When the try block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code continues execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.
PHP 5 provides basic exception handling classes that can be used directly.
<?php class Exception { protected $message = 'Unknown exception'; // 异常信息 protected $code = 0; // 用户自定义异常代码 protected $file; // 发生异常的文件名 protected $line; // 发生异常的代码行号 function __construct($message = null, $code = 0); final function getMessage(); // 返回异常信息 final function getCode(); // 返回异常代码 final function getFile(); // 返回发生异常的文件名 final function getLine(); // 返回发生异常的代码行号 final function getTrace(); // backtrace() 数组 final function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息 /* 可重载的方法 */ function __toString(); // 可输出的字符串 } ?>
Throw an error message through exception:
try { $error = 'my error!'; throw new Exception($error) } catch (Exception $e) { echo $e->getMessage(); }
We can extend this class to facilitate our use:
class MyException extends Exception { // 重定义构造器使 message 变为必须被指定的属性 public function __construct($message, $code = 0) { // 自定义的代码 // 确保所有变量都被正确赋值 parent::__construct($message, $code); } // 自定义字符串输出的样式 public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; } public function customFunction() { echo "A Custom function for this type of exception\n"; } }
This class can be extended and used according to your needs.