code}]: {$this->message}\n"; }}/*** 创建一">
当前位置:Gxlcms > PHP教程 > 一个简单的php自定义异常类

一个简单的php自定义异常类

时间:2021-07-01 10:21:17 帮助过:13人阅读

  1. /**

  2. * 自定义一个异常处理类
  3. */
  4. class MyException extends Exception
  5. {
  6. // 重定义构造器使 message 变为必须被指定的属性
  7. public function __construct($message, $code = 0) {
  8. // 自定义的代码
  9. // 确保所有变量都被正确赋值
  10. parent::__construct($message, $code);
  11. }
  12. // 自定义字符串输出的样式
  13. public function __toString() {
  14. return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
  15. }
  16. }

  17. /**

  18. * 创建一个用于测试异常处理机制的类
  19. */
  20. class TestException
  21. {
  22. function __construct($str) {
  23. if($str == 1)
  24. throw new MyException('参数不能为1哦',1);
  25. elseif($str == 2)
  26. throw new MyException('参数不能为2哦',2);//抛出2个异常
  27. else
  28. echo $str;
  29. }
  30. }

  31. try {

  32. $o = new TestException(2);
  33. } catch (MyException $e) { // 捕获异常
  34. echo $e;
  35. }
  36. ?>

人气教程排行