Exception Handling in PHP

Source: Internet
Author: User
Tags try catch

1. What is an exception? What is the difference between an exception and an error?

1. Exception: program operation is not consistent with expectations, and errors are two different concepts!
2. Throwing and catching exceptions
3. Multiple catch blocks when the base class is to be placed back, or the base class catches the exception will not continue to capture!
3. First error occurs, in the event of an exception, so write the API must turn off the Display_errors
4.php built-in exception

Error_reporting ( -1); Ini_set (' display_errors ', ' off ');//pdo built-in exception class try {    $pdo = new PDO (' Mysql:host=localhost; Dbname=mysql ', ' brave ', ' 123456 ');    Var_dump ($PDO);    Echo '
 
  ';    Echo ' Continue ... ';} catch (Exception $e) {    echo $e->getmessage ();} Echo ' This is a test ... '; Echo '
 
  ';//spl file read-write built-in exception class try {    $splObj = new Splfileobject (' Test.txt ', ' R ');    Echo ' read file ';} catch (RuntimeException $e) {    echo $e->getmessage ();} Echo ' Continue ... '; Echo '
 
  ';

2. The basic grammatical structure of the exception

    The try {        //code that requires exception handling        throws the throw statement    } catch (Pdoexception $e) {        try {             throw statement throws        } catch (Exception $e {        }    } catch (Fileexception $e) {    } catch (Customexception $e) {    }    //other Code

3. How do I customize the exception class?

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 = "

An exception occurred with the following information

"; $message. = "

". __class__." [{$this->code}]:{$this->message}

"; return $message; } Public Function test () { echo ' This is a test '; } Public Function Stop () { exit (' Script end ...... '); } Custom other methods}try { echo ' has an exception! '; throw new MyException ("Test custom Exception! ", 11);} catch (MyException $e) { echo $e->getmessage (); Echo ' '; echo $e; Echo ' '; $e->stop (); $e->test ();}

4. custom file Exception class

Error_reporting ( -1); Ini_set (' display_errors ', ' off '); class Fileexception extends Exception {public function Getdetails () {switch ($this->code) {case 0:return ' does not provide a file!                ';            Break Case 1:return ' file does not exist!                '. ' Trace '. $this->gettraceasstring (). $this->getline ();            Break Case 2:return ' is not a file!                '. ' Trace '. $this->gettraceasstring (). $this->getline ();            Break Case 3:return ' file is not writable!                ';            Break Case 4:return ' illegal file operation mode!                ';            Break Case 5:return ' data write failed!                ';            Break Case 6:return ' file cannot be closed!                ';            Break Default:return ' Illegal!                ';        Break    }}}class writedata{private $_message= ";    Private $_fp=null; Public function __construct ($filename =null, $mode = ' W '{$this->_message= "file: {$filename} mode: {$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 Write Data] * @param [Type] $data [description] * @return [type] [description] */Public Function write ($dat A) {if (@!fwrite ($this->_fp, $data.        Php_eol) {throw new Fileexception ($this->_message, 5); }}/** * [close closed file handle] * @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 ' data is written successfully! ';} catch (Fileexception $e) {echo ' has a problem: '. $e->getmessage (). ' Details are as follows: '. $e->getdetails ();}

5. Handling exceptions by using the Observer pattern

    1. A class that defines observations (exceptions) that you can dynamically add observers to in your code
    /** * Observation (Exception) class, you can dynamically add the observer in the code */    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. Define the anomaly Observer base class , which is used to standardize each observer

    /** * Observer base class, used to standardize each observer    /interface exception_observer{        //Mandatory designation must be the Observation class public function update we have specified        ( Observable_exception $e);    }

3. Define Log Watcher

    /** * Define Log Viewer */    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 = "Time:". Date (' y-m-d h:i:s '). Php_eol;            $message. = "INFO:". $e->getmessage (). Php_eol;            $message. = "Tracking information:". $e->gettraceasstring (). Php_eol;            $message. = "File:". $e->getfile (). Php_eol;            $message. = ' line number: '. $e->getline (). Php_eol;            Error_log ($message, 3, $this->_filename);        }    }

4. Define the Message Viewer

    /** * Define Message Viewer */    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 = "Time:". Date (' y-m-d h:i:s '). Php_eol;            $message. = "INFO:". $e->getmessage (). Php_eol;            $message. = "Tracking information:". $e->gettraceasstring (). Php_eol;            $message. = "File:". $e->getfile (). Php_eol;            $message. = ' line number: '. $e->getline (). Php_eol;            Error_log ($message, 1, $this->_email);        }    }

5. Perform the test

Error_reporting ( -1); Ini_set (' display_errors ', ' off ');//Introduce the class require ' observable_exception.php ' that observe the anomaly;// Introducing the Observer base class require ' exception_observer.php ';//Introducing the Log Viewer require ' logging_exception_observer.php ';//introducing the Email watcher require ' email _exception_observer.php '; Observable_exception::attach (new Logging_exception_observer ());//Custom address record error exception Observable _exception::attach (New Logging_exception_observer ('/tmp/test11.log ')); Observable_exception::attach (New Email_ Exception_observer ());//Custom message recipient record Error exception Observable_exception::attach (new Email_exception_observer (' 123456@qq.com ') )); class MyException extends observable_exception{public    function test () {        echo ' a test! ';    }    Public Function test1 () {        echo ' I'm a custom method to handle this exception! ';    }} try {    throw new MyException ("There's an exception, record it! ");} catch (MyException $e) {    echo $e->getmessage ();    Echo '
 
  ';    $e->test ();    Echo '
 
  ';    $e->test1 ();}

6. Custom Exception Processor (Set_exception_handler)?

1. Purpose 1 handles all uncaught exceptions
2. Purpose 2 handles all of the exceptions we put into the try Catch

3. Custom Exception Handling functions

Ini_set (' display_errors ', ' off '), function exceptionhandler_1 ($e) {  echo ' custom exception Processor 1 '. __function__;  Echo ' Exception information: '. $e->getmessage ();} function exceptionhandler_2 ($e) {  echo ' custom exception Processor 2 '. __function__;  Echo ' Exception information: '. $e->getmessage ();} Set_exception_handler (' exceptionhandler_1 '); Set_exception_handler (' exceptionhandler_2 ');// Revert to the last defined exception handler Restore_exception_handler (); throw new Exception (' Test '); Echo ' Continue ... '; Echo '
 
  ';

4. Custom Exception Handling classes

/** * Custom Error Exception class */class exceptionhandler{protected $_exception;    Protected $_logfile= './testexceptionhandler.log ';    function __construct (Exception $e) {//Save exception object $this->_exception = $e;        public static function handle (Exception $e) {$self = new self ($e);        $self->log ();    Echo $self; Public Function log () {$msg =<<
 
  
   _exception->getfile ()}
   
The message that generated the notification: {$this->_exception->gettraceasstring ()} The line number that generated the notification: {$this->_exception->getline ()} The error number that generated the notification: {$ This->_exception->getcode ()} Time to generate notification: {$datetime} \ n EOF; Echo $msg; Error_log ($msg, 3, $this->_logfile); } public Function __tostring () {$message = <<

An exception has occurred .....

Refresh next Try

EOF; return $message; }}ini_set (' display_errors ', ' off '); Set_exception_handler (Array (' Exceptionhandler ', ' handle ');//Put in try Throwtry {throw new Exception in catch ("This is a test!", 20010),} catch (Exception $e) {echo $e->getmessage ();} Throwthrow new Exception not placed in the try catch ("Test for uncaught custom exception handler Hello world!", 2008);

7. How do I handle PHP errors as you do with exceptions?

1. By 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. Custom exception Classes

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. Redirect the user to another page when an error occurs

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, 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 ("The database is under attack, go and see it!") ");}

9. Set parameters to be passed for custom errors and exceptions

Exception delivery: $msg, $code
Error delivery: $errno, $errmsg, $errfile, $errline can see myerrorhandler.php

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.