Heim  >  Artikel  >  Backend-Entwicklung  >  一个简单的php自定义异常类

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

WBOY
WBOYOriginal
2016-07-25 09:03:592119Durchsuche
  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. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn