Home > Backend Development > PHP Tutorial > Several ways to use PHP custom exception handler_PHP tutorial

Several ways to use PHP custom exception handler_PHP tutorial

WBOY
Release: 2016-07-15 13:32:21
Original
961 people have browsed it

Handling exceptions in

The following 4 pieces of code are my simple applications in the waylife project (non-production environment). They are not robust or beautiful, but the SNS project Already died in infancy.

1. Hierarchical relationship of exception classes:

  1. class NotFoundException extends Exception{}
  2. class InputException extends Exception{}
  3. class DBException extends Exception{}


2. Configure the handler for uncaught exceptions:

  1. function exception_uncaught_handler(Exception $e) {
  2. header ('Content-type: text/html; charset=utf- 8');
  3. if ($e instanceof NotFoundException)
  4. exit($e->getMessage());
  5. elseif ($e instanceof DBException)
  6. exit($e->getMessage());
  7. else
  8. exit($e->getMessage());
  9. }
  10. set_exception_handler('exception_uncaught_handler');

3. In the database Connect the code and manually throw the DBException exception but do not use try...catch to catch it. The exception will be handled by the PHP custom exception handler exception_uncaught_handler() function:

  1. $this->resConn = mysql_connect ($CONFIGS['db_host'], $CONFIGS['db_user'], $CONFIGS['db_pwd']);
  2. if (false == is_resource($this-> resConn))
  3. throw new DBException('Database connection failed. '.mysql_error($this->resConn));


4. Business logic at a glance:

  1. if (0 != strcmp($curAlbum->interest_id, $it))
  2. throw new NotFoundException('Sorry, The photo album you visited does not exist');

The above is the specific use of PHP custom exception handler.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446148.htmlTechArticleHandling exceptions in the following 4 pieces of code is my simple application in the waylife project (non-production environment), which is not robust Not to beautify it, but the SNS project has long since died. 1. Hierarchical relationship of exception classes...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template