Home  >  Article  >  Backend Development  >  A simple php custom exception class

A simple php custom exception class

WBOY
WBOYOriginal
2016-07-25 09:03:592156browse
  1. /**

  2. * Customize an exception handling class
  3. */
  4. class MyException extends Exception
  5. {
  6. // Redefine the constructor to make message a property that must be specified
  7. public function __construct ($message, $code = 0) {
  8. // Customized code
  9. // Make sure all variables are assigned correctly
  10. parent::__construct($message, $code);
  11. }
  12. // Customized string output Style
  13. public function __toString() {
  14. return __CLASS__ . ": [{$this->code}]: {$this->message}n";
  15. }
  16. }

  17. * Create a class for testing exception handling mechanism
  18. */
  19. class TestException
  20. {
  21. function __construct($str) {
  22. if($str == 1)
  23. throw new MyException('The parameter cannot be 1',1);
  24. elseif( $str == 2)
  25. throw new MyException('The parameter cannot be 2',2);//Throw 2 exceptions
  26. else
  27. echo $str;
  28. }
  29. }

  30. try {

  31. $o = new TestException(2);
  32. } catch (MyException $e) { // Catch exception
  33. echo $e;
  34. }
  35. ?>

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn