Exception Handling in PHP ____php

Source: Internet
Author: User
Tags exception handling getmessage
1. What is an exception. What is the difference between an exception and an error.

1. Exceptions: The program runs in a less consistent way than expected, and the error is two different concepts.
2. Throwing and catching exceptions
3. When multiple catch blocks are set, the base class is placed backward, otherwise the base class catches the exception and does not continue to capture.
3. First error, in the 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 ' 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18-------------19 20 21 22 23 24 25 26 1-2 3 4 5, 6 22 23 24 25 26 2. The basic grammatical structure of the anomaly
    try {
        //code Throw statement that requires exception handling
        throw
    } catch (Pdoexception $e) {

        try {
             throw statement throw
        } catch (Exception $e ' {

        }

    ' catch (fileexception $e) {

    } catch (Customexception $e) {

    }

    //other Code
1, 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 3. How to customize the Exception class.
error_reporting ( -1); Ini_set (' display_errors ', ' off '); class MyException extends
    function __construct ($message, $code =0) {parent::__construct ($message, $code);
        The Public Function __tostring () {$message = "
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18-------------19 20 21 22 23 24 25 26 27-28 29 30 31, 32 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 ' no documentation provided.
                ';

            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 mode of operation.
                ';

            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 ', ' + '))} {throw new Fileexception ($this->_message, 4);
    $this->_fp=fopen ($filename, $mode);
    /** * [Write Data] * @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 closes file handle] * @return [type] [description]/Public function closing () {if ($this
                ->_FP) {if (@!fclose ($this->_fp)) {throw new Fileexception ($this->_message, 6);
            $this->_fp=null;
    The Public Function __destruct () {$this->close ()}}
    } try {$fp = new WriteData (' Test.txt ', ' W ');
    $FP->write (' is a test ');
    $FP->close (); Echo ' data write succeeded.
'; There was a problem with catch (Fileexception $e) {echo: '. $e->getmessage (). ' Details are as follows: '. $e->getdetails ();}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 1 2 3 4 5 6 7 8 9 10 11 12 13 14 A. 3 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 3 104 5. Handling exceptions using the Observer patternA class that defines observations (exceptions) that can be dynamically added to the viewer in code
    /**
     * Observation (Exception) of the 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);
            }

    }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1 2 3 4-5--6 7---8 9--10 11 12 13 14 15 16-17 18 19 20

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{
        //force designation must be the observed class public function that we specify
        Update (Observable_exception $e);

    }
1 2 3 4 5 6 7 8 1 2 3 4 5 6-7 8

3. Define Log Viewer

    /**
     * Definition log Observer/
    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. = "Information:". $e->getmessage (). Php_eol;
            $message. = "Trace Information:". $e->gettraceasstring (). Php_eol;
            $message. = "File:". $e->getfile (). Php_eol;
            $message. = ' line number: '. $e->getline (). Php_eol;
            Error_log ($message, 3, $this->_filename);
        }
    
1-2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20 21 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20

4. Define Message Viewer

    /**
     * Defines 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. = "Information:". $e->getmessage (). Php_eol;
            $message. = "Trace Information:". $e->gettraceasstring (). Php_eol;
            $message. = "File:". $e->getfile (). Php_eol;
            $message. = ' line number: '. $e->getline (). Php_eol;
            Error_log ($message, 1, $this->_email);
        }
    
1-2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20 21 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19-20

5. Test execution

error_reporting ( -1); Ini_set (' display_errors ', ' off ');//introduction of the class of observed anomalies require ' observable_
Exception.php '; 

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.