Home> php教程> php手册> body text

PHP自定义异常处理器的几种使用方法

WBOY
Release: 2016-06-13 11:09:23
Original
1202 people have browsed it

处理异常在

以下4段代码为我在waylife项目中的简单应用(非生产环境),不健壮也不美化,但该SNS项目早已经夭折。

1、异常类的层级关系:

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


2、配置未捕捉异常的处理器:

  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、在数据库连接代码,手动抛出DBException异常但未使用try…catch进行捕获处理,该异常将被PHP自定义异常处理器exception_uncaught_handler()函数处理:

  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('数据库连接失败。'.mysql_error($this->resConn));


4、业务逻辑一瞥:

  1. if (0 != strcmp($curAlbum->interest_id, $it))
  2. throw new NotFoundException('很抱歉,你所访问的相册不存在');

以上就是PHP自定义异常处理器的具体使用方法。


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 Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!