Errors encountered by PHP programmers and exceptions to the next chapter of the exception

Source: Internet
Author: User
Tags parse error try catch
This article introduces the content of the PHP programmer encountered errors and anomalies in the exception, now share to everyone, the need for friends can refer to

Previous: Those years, Phper encountered errors and exceptions: The error of the previous article

I. Introduction and use of exceptions in PHP

1.1 Exception Execution Process

try{    //code snippet that requires exception handling; Throw    statement throws an exception;}catch (Exception $e) {    ...} catch (Exception $e) {    //Handle exception}contine .....

An uncaught exception will report a fatal error:Fatal error:Uncaught exception.....

1.2 PHP Exception Features

    1. PHPThe exception is not actively caught and requires an unsolicited () exception in the program to be throw captured.

    2. throwwill automatically throw up

    3. throwThe following statement does not execute

    4. tryAfter must have catch , otherwise parse errorParse error

try{    $num 1=3;    $num 2=0;    if ($num 2==0) {        throw new Exception (' 0 cannot be counted as divisor ');        Echo ' This is a test ';//Cannot see    }else{        $res = $num 1/$num 2;    }} catch (Exception $e) {    echo $e->getmessage ();}

1.3 PHP Built-in exceptions

PhpUnlike java providing a lot of exception classes, many exceptions will be treated as errors. To change the error to throw an exception, a manual throw exception object is required

PHP built-in exceptions such as: PDOException , SplFileObject can automatically throw an exception, the following code can continue to execute.

1.4 Differences between errors and exceptions

1.4.1 Exception Handling

When the exception is thrown throw , the following code will not proceed , and PHP will attempt to find a matching catch block of code. If the exception is not captured and is not used set_exception_handler() for the appropriate processing, a serious error ( fatal error ) will occur and an Uncaught Exception error message "" (uncaught exception) is output.

Basic grammatical structure of 1.4.2 anomalies

try -code that requires exception handling should be placed try inside a block of code to catch a potential exception. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown
throw-this specifies how the exception is triggered. Each try or throw 必须 corresponds to at least one catch. You can use multiple catch blocks to catch different kinds of exceptions.
catch- Catch code block catches an exception and creates an object containing the exception information

1.4.3 Re-throwing exceptions

Sometimes, when an exception is thrown, you might want to handle it in a different way from the standard. You can throw an exception again in a catch code block. 注意再次抛出异常需要try{}catch{},不能直接在catch代码块中throw异常.

The script should hide the system error from the user. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can again throw exceptions with a friendly message to the user.
In short: If an exception is thrown, it must be captured.

1.4.4 the difference between an error and an exception

Exception: program run is not consistent with expectations

Error: The trigger is an error of its own

    • When an error is encountered, it is triggered by its own error and does not automatically throw an exception. Exceptions can be throw thrown through a statement by catch catching an exception, which could cause a fatal error if not captured.

    • The script must be processed immediately when the error occurs or when it is triggered. Exceptions can be passed up and down until they are captured and processed.

    • The error trigger does not have a related code or name. Exceptions can be customized to handle error messages (the benefits of exceptions are manifested), are thrown through code, captured and then processed

Second, custom exception class

2.1 Custom Exception Classes

    1. Custom exception Classes can only override constructors and toString two functions

    2. Custom exception classes can add their own methods

    3. catchwhen multiple, the general Exception base class is placed at the end, the base class can invoke the method defined by the custom exception class

/** * Custom Exception classes * Class MyException */class myexception extends exception{public fu Nction __construct ($message = "", $code = 0, throwable $previous = null) {parent::__construct ($message, $code,    $previous);        The Public Function __tostring () {$message = "
try{    throw new myexception (' Test custom exception ');} catch (Exception $exception) {    echo $exception->getmessage ();    $exception->test ();} catch (MyException $exception) {    echo $exception->getmessage ();}

2.2 Tips

The error is absorbed with the error suppressor and then throws an exception if (@!fwrite ($filename, $data)) throw new Exception (custom exception) Php_eol #换行符

Logging error log information:

(1):file_put_contents(LOG_PATH.'error.log';, '错误信息'.' '.date('Y-m-d H:i:s')."\r\n", FILE_APPEND);

(2):error_log('错误信息'.' '.date('Y-m-d H:i:s')."\r\n",3,LOG_PATH.'error.log');

2.3 Handling exception information by using the Observer pattern

exception_observer.php/** * Define specifications for Observers * * Interface exception_observer */interface exception_observer{public    function Update (observable_exception $e);}
observable_exception.php/** * Define Observer * Class Observable_exception */class    Observable_exception extends exception{//save observer Information public static $_observers = Array ();    public static function Attach (Exception_observer $observer) {self::$_observers[] = $observer; The Public function __construct ($message = "", $code = 0, throwable $previous = null) {parent::__construct ($me        Ssage, $code, $previous);    $this->notify (); The Public Function notify () {foreach (self::$_observers as $observer) {$observer->update ($this        ); }    }}
logging_exception_observer.php/** * Logging error log * class Logging_exception_observer */class Logging_exception_observer implements exception_observer{protected $_filename = __dir__. '    /error_observer.log ';            Public function __construct ($filename = null) {if ($filename!==null && is_string ($filename)) {        $this->_filename = $filename; The 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);//write to the log}} 
test.php/** * Test */header (' Content-type:text/html;charset=utf-8 '); require_once ' exception_observer.php '; require_ Once ' logging_exception_observer.php '; require_once ' observable_exception.php '; Observable_exception::attach (new Logging_exception_observer ()); class MyException extends observable_exception{public    function test ()    {        Echo ' This is a test ';    }} try{    throw new MyException (' There's an exception! ');} catch (MyException $exception) {    echo $exception->getmessage ();}

Iii. Custom Exception handlers

3.1 How to customize exception handlers

3.1.1 Custom Exception handlers

    1. Similar to the error handler of the Set_error_handler takeover system, Set_exception_handler take over all exceptions that are not catch

    2. restore_exception_handler with restore_error_ Handler , you should essentially pop one out of the exception/error handling function stack. For example, there is an exception handler function, pop-up, there is no exception handler function, if there is an exception is not captured, will be left to the error handling function, such as no error handling function, the exception will eventually have the system error handling function processing. If 2 exception handlers are set, a popup will be processed by one of the following exception handling functions.

/** * Custom Exception function Processor */header (' content-type:text/html;charset=utf-8 '); function Exceptionhandler_1 ($e) {echo ' custom exception handler 1<br/> function name: '. __function__.    Php_eol; Echo ' Exception information: '. $e->getmessage ();} function exceptionhandler_2 ($e) {echo ' custom exception handler 2<br/> functions name: '. __function__.    Php_eol; Echo ' Exception information: '. $e->getmessage ();} Set_exception_handler (' exceptionhandler_1 ');//set_exception_handler (' exceptionhandler_2 ');//revert to the last defined exception handler, That is Exceptionhandler_1//restore_exception_handler ();//Fatal error message//restore_exception_handler (); throw new Exception (' Test custom exception handler ');//Custom exception handler, do not continue execution downward, because the throw will not continue after the execution; try{} catch{}, will continue to perform//review: Custom error handler will continue to execute code, The error message that is manually thrown does not continue to execute echo ' test '; 
/** * Custom Exception class processor * Class Exceptionhandler */class exceptionhandler{protected $_exception; protected $_logfile = __dir__. '    /exception_handle.log ';    Public function __construct (Exception $e) {$this->_exception = $e;        public static function handle (Exception $e) {$self = new self ($e);        $self->log ();    Echo $self; Public Function log () {Error_log ($this->_exception->getmessage ().    php_eol,3, $this->_logfile);     }/** * Magic Method __tostring () * quick way to get the string information of an object, directly outputting the method that is called automatically when the object is referenced. * @return String */Public Function __tostring () {$message = <<<eof <! DOCTYPE html> 

3.1.2 Error/exception to continue execution of code issues summary

Abnormal:

The custom exception handler does not continue down because it throw will no longer execute
try{} catch{}After that, the execution will continue

Error:

custom error handlers continue to execute code, and manually thrown error messages do not continue

3.2 Handling PHP errors like handling exceptions

3.2.1 Way One: errorexception

/** * Way One: Errorexception Error Exception class * @param $errno * @param $errstr * @param $errfile * @param $errline * @throws errorexceptio N */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 $exception) {    echo $exception->getmessage ();}

3.2.2 Method Two: Custom exception class, Inherit base class exception

/** * Way Two: Custom Exception class * Classes Errortoexception *///Show all Errors error_reporting ( -1); class Errortoexception extends exception{    public static function handle ($errno, $errstr)    {        throw new self ($errstr, 0);}    } Set_error_handler (Array (' errortoexception ', ' handle ')), Set_error_handler (Array (' errortoexception ', ' handle '), E_ User_warning| e_warning); try{    echo $test;//notice, will not be processed by    Echo GetType ();//warning    //Manual Trigger Error    trigger_error (' Test ' , e_user_warning);} catch (Exception $exception) {    echo $exception->getmessage ();}

3.3 PHP page Redirection implementation

Header (' Content-type:text/html;charset=utf-8 '); class exceptionredirecthandler{protected $_exception; protected $_logfile = __dir__. '    Redirect.log ';    Public $redirect = ' 404.html ';    Public function __construct (Exception $e) {$this->_exception= $e;        The public static function handle (Exception $e) {$self the =new self ($e);        $self->log ();        Ob_end_clean () Clears all output buffers, and at the end of the time there is a notification level error when there is no cache while (@ob_end_clean ()); Header (' http/1.1 307 temporary Redirect ');        Temporary REDIRECT Header (' Cache-control:no-cache,must-revalidate ');//no-cache force re-authentication to the source server, Must-revalidate cacheable but must be confirmed to the source server again Header (' Expires:sat, 13:28:48 GMT '); Resource Expiration Time Header (' Location: '. $self->redirect); Jump} public Function log () {Error_log ($this->_exception->getmessage ().    php_eol,3, $this->_logfile); }}set_exception_handler (Array (' Exceptionredirecthandler ', ' handle ')); $link = @mysqli_connect (' 127.0.0.1 ', ' root ', ' 1234561 '); if (! $link) {Throw New Exception (' Database connection error ');} 

Finish!

Reference Course Videos: Mistakes and anomalies you've encountered in those years

Related recommendations:

Errors encountered by PHP programmers and errors in the exception of the previous article

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.