目錄
1.什么是异常?异常和错误有什么区别?
2.异常的基本语法结构
3.如何自定义异常类?
出现异常了,信息如下
4.自定义文件异常类
5.使用观察者模式处理异常
6.自定义异常处理器(set_exception_handler)?
3.自定义异常处理函数
4.自定义异常处理类
出现异常了。。。。。
7.如何像处理异常一样处理PHP的错误?
8.在发生错误的时候将用户重定向到另一个页面
9.设置自定义错误和异常需要传递的参数
首頁 後端開發 php教程 PHP中的异常处理

PHP中的异常处理

Jun 23, 2016 pm 01:30 PM
php中的異常處理

1.什么是异常?异常和错误有什么区别?

1.异常:程序运行与预期不太一致,与错误是两个不同的概念!
2.抛出和捕获异常
3.多个catch块的时候基类要往后放,否则基类捕获异常后就不会往下继续捕获了!
3.先出现错误,在出现异常,所以写api的时候一定要把display_errors关掉
4.php的内置异常

error_reporting(-1);ini_set('display_errors','off');//pdo内置异常类try {    $pdo = new PDO('mysql:host=localhost;dbname=mysql', 'brave', '123456');    var_dump($pdo);    echo '<hr/>';    echo 'continue.......';} catch (Exception $e) {    echo $e->getMessage();}echo 'this is a test.......';echo '<hr/>';//spl文件读写内置异常类try {    $splObj = new SplFileObject('test.txt', 'r');    echo 'read file';} catch (RuntimeException $e) {    echo $e->getMessage();}echo 'continue.......';echo '<hr/>';
登入後複製

2.异常的基本语法结构

    try {        //需要进行异常处理的代码        throw语句抛出    } catch (PdoException $e) {        try {             throw语句抛出        } catch (Exception $e) {        }    } catch (FileException $e) {    } catch (CustomException $e) {    }    //other code
登入後複製

3.如何自定义异常类?

error_reporting(-1);ini_set('display_errors','off');class MyException extends Exception{    function __construct($message, $code=0) {        parent::__construct($message, $code);    }    public function __toString(){        $message = "<h2 id="出现异常了-信息如下">出现异常了,信息如下</h2>";        $message .="<p>".__CLASS__." [{$this->code}]:{$this->message}</p>";        return $message;    }    public function test(){        echo 'this is a test';    }    public function stop(){        exit('script end..............<hr/>');    }    //自定义其他方法}try {    echo '出现异常了!';    throw new MyException("测试自定义异常!", 11);} catch (MyException $e) {    echo $e->getMessage();     echo '<hr/>';    echo $e;    echo '<hr/>';    $e->stop();    $e->test();}
登入後複製

4.自定义文件异常类

error_reporting(-1);ini_set('display_errors','off');class FileException extends Exception {    public function getDetails() {        switch ($this->code) {            case 0:                return '没有提供文件!';                break;            case 1:                return '文件不存在!'." trace".$this->getTraceAsString().$this->getLine();                break;            case 2:                return '不是一个文件!'." trace".$this->getTraceAsString().$this->getLine();                break;            case 3:                return '文件不可写!';                break;            case 4:                return '非法文件的操作模式!';                break;            case 5:                return '数据写入失败!';                break;            case 6:                return '文件不能被关闭!';                break;            default:                return '非法!';                break;        }    }}class WriteData{    private $_message='';    private $_fp=null;    public function __construct($filename=null, $mode='w'){        $this->_message="文件:{$filename} 模式:{$mode}";        if (empty($filename)) {            throw new FileException($this->_message, 0);        }        if (!file_exists($filename)) {            throw new FileException($this->_message, 1);        }        if (!is_file($filename)) {            throw new FileException($this->_message, 2);        }        if (!is_writable($filename)) {            throw new FileException($this->_message, 3);        }        if (!in_array($mode, array('w', 'w+', 'a', 'a+'))) {            throw new FileException($this->_message, 4);        }        $this->_fp=fopen($filename, $mode);    }    /** * [write 写数据] * @param [type] $data [description] * @return [type] [description] */    public function write($data){        if (@!fwrite($this->_fp, $data.PHP_EOL)) {            throw new FileException($this->_message, 5);        }    }    /** * [close 关闭文件句柄] * @return [type] [description] */    public function close(){        if ($this->_fp) {            if (@!fclose($this->_fp)) {                throw new FileException($this->_message, 6);                $this->_fp=null;            }        }    }    public function __destruct(){        $this->close();    }}try {    $fp = new WriteData('test.txt', 'w');    $fp->write('this is a test');    $fp->close();    echo '数据写入成功!';} catch (FileException $e) {    echo '出问题了:'.$e->getMessage().' 详细信息如下:'.$e->getDetails();}
登入後複製

5.使用观察者模式处理异常

  1. 定义观察(异常)的类, 可以在代码中动态的添加观察者
    /** * 观察(异常)的类, 可以在代码中动态的添加观察者 */    class Observable_Exception extends Exception {        public static $_observers=array();        public static function attach(Exception_Observer $observer){            self::$_observers[]=$observer;        }        public function __construct($message=null, $code=0){            parent::__construct($message, $code);            $this->notify();        }        public function notify(){            foreach (self::$_observers as $observer) {                $observer->update($this);            }        }    }
登入後複製

2.定义异常观察者基类,用于规范每一个观察者

    /** * 观察者基类,用于规范每一个观察者 */    interface Exception_Observer{        //强制指定必须是我们规定的观察类        public function update(Observable_Exception $e);    }
登入後複製

3.定义日志观察者

    /** * 定义日志观察者 */    class Logging_Exception_Observer implements Exception_Observer{        public $_filename='./log_exception.log';        public function __construct($filename=null){            if ($filename!==null && is_string($filename)) {                $this->_filename=$filename;            }        }        public function update(Observable_Exception $e){            $message="时间:".date('Y-m-d H:i:s').PHP_EOL;            $message.="信息:".$e->getMessage().PHP_EOL;            $message.="追踪信息:".$e->getTraceAsString().PHP_EOL;            $message.="文件:".$e->getFile().PHP_EOL;            $message.='行号:'.$e->getLine().PHP_EOL;            error_log($message, 3, $this->_filename);        }    }
登入後複製

4.定义邮件观察者

    /** * 定义邮件观察者 */    class Email_Exception_Observer implements Exception_Observer{        public $_email='732578448@qq.com';        public function __construct($email=null){            if ($email!==null && filter_var($email, FILTER_VALIDATE_EMAIL)) {                $this->_email=$email;            }        }        public function update(Observable_Exception $e){            $message="时间:".date('Y-m-d H:i:s').PHP_EOL;            $message.="信息:".$e->getMessage().PHP_EOL;            $message.="追踪信息:".$e->getTraceAsString().PHP_EOL;            $message.="文件:".$e->getFile().PHP_EOL;            $message.='行号:'.$e->getLine().PHP_EOL;            error_log($message, 1, $this->_email);        }    }
登入後複製

5.执行测试

error_reporting(-1);ini_set('display_errors','off');//引入观察异常的类require 'Observable_Exception.php';//引入观察者基类require 'Exception_Observer.php';//引入日志观察者require 'Logging_Exception_Observer.php';//引入邮件观察者require 'Email_Exception_Observer.php';Observable_Exception::attach(new Logging_Exception_Observer());//自定义地址记录错误异常Observable_Exception::attach(new Logging_Exception_Observer('/tmp/test11.log'));Observable_Exception::attach(new Email_Exception_Observer());//自定义邮件接收人记录错误异常Observable_Exception::attach(new Email_Exception_Observer('123456@qq.com'));class MyException extends Observable_Exception{    public function test(){        echo 'this is a test!';    }    public function test1(){        echo '我是 自定义的方法处理这个异常!';    }}try {    throw new MyException("出现异常了,记录一下下!");} catch (MyException $e) {    echo $e->getMessage();    echo '<hr/>';    $e->test();    echo '<hr/>';    $e->test1();}
登入後複製

6.自定义异常处理器(set_exception_handler)?

1.目的1处理所有未捕获的异常
2.目的2处理所有我们为放到try catch中的异常

3.自定义异常处理函数

ini_set('display_errors','off');function exceptionHandler_1($e){  echo '自定义异常处理器1'.__FUNCTION__;  echo '异常信息:'.$e->getMessage();}function exceptionHandler_2($e){  echo '自定义异常处理器2'.__FUNCTION__;  echo '异常信息:'.$e->getMessage();}set_exception_handler('exceptionHandler_1');set_exception_handler('exceptionHandler_2');//恢复到上一次定义过的异常处理函数restore_exception_handler();throw new Exception('测试');echo 'continue........';echo '<hr/>';
登入後複製

4.自定义异常处理类

/** * 自定义错误异常类 */class ExceptionHandler{    protected $_exception;    protected $_logFile='./testExceptionHandler.log';    function __construct(Exception $e){        //保存异常对象        $this->_exception = $e;    }    public static function handle(Exception $e){        $self = new self($e);        $self->log();        echo $self;    }    public function log(){        $msg=<<<EOF 出现了通知错误,如下 产生通知的文件:{$this->_exception->getFile()}<br> 产生通知的信息:{$this->_exception->getTraceAsString()} 产生通知的行号:{$this->_exception->getLine()} 产生通知的错误号:{$this->_exception->getCode()} 产生通知的时间:{$datetime} \n EOF;        echo $msg;        error_log($msg, 3, $this->_logFile);    }    public function __toString(){        $message = <<<EOF <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1 id="出现异常了">出现异常了。。。。。</h1> <p>刷新下试试</p> </body> </html> EOF;        return $message;    }}ini_set('display_errors','off');set_exception_handler(array('ExceptionHandler', 'handle'));//放在try catch中的throwtry {    throw new Exception("this is a test!",20010);} catch (Exception $e) {    echo $e->getMessage();}//没放在try catch中的throwthrow new Exception("测试未捕获的自定义的异常处理器hello world!",2008);
登入後複製

7.如何像处理异常一样处理PHP的错误?

1.通过ErrorException

function exception_error_handler($errno, $errstr, $errfile, $errline){    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);}set_error_handler('exception_error_handler');try {    echo gettype();} catch (Exception $e) {    echo $e->getMessage();}
登入後複製

2.自定义异常类

class ErrorToException extends Exception{    public static function handle($errno, $errstr) {        throw new self($errstr, $errno);    }}ini_set('display_errors', 'off');set_error_handler(array('ErrorToException', 'handle'));set_error_handler(array('ErrorToException', 'handle'),E_USER_WARNING|E_WARNING);try {    echo $test;    gettype();    trigger_error('test',E_USER_WARNING);} catch (Exception $e) {    echo $e->getMessage();}
登入後複製

8.在发生错误的时候将用户重定向到另一个页面

class ExceptionRedirectHandler{    protected $_exception;    protected $_logFile='./redirectLog.log';    protected $_redirect='404.html';    public function __construct(Exception $e){        $this->_exception=$e;    }    public static function handle(Exception $e){        $self = new self($e);        $self->log();        while (@ob_end_clean());        header('HTTP/1.1 307 Temporary Redirect');        header('Cache-Control:no-cache,must-revalidate');        header('Expires: Wed, 01 Jul 2015 07:40:45 GMT');        header('Location:'.$self->_redirect);        exit(1);    }    public function log($value=''){        error_log($this->_exception->getMessage().PHP_EOL, 3, $this->_logFile);    }}ini_set('display_errors','off');set_exception_handler(array('ExceptionRedirectHandler', 'handle'));$link = mysql_connect('localhost', 'brave', '123456123');if (!$link) {    throw new Exception("数据库受到攻击了,赶快去看看吧!");}
登入後複製

9.设置自定义错误和异常需要传递的参数

异常传递:$msg, $code
错误传递:$errno, $errmsg, $errfile, $errline 可看MyErrorHandler.php

版权声明:本文为博主原创文章,未经博主允许不得转载。

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1423
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

See all articles