Extends the PHP built-in exception handling class and php built-in exception handling _ PHP Tutorial

Source: Internet
Author: User
Tags php exception handling
Extends the PHP built-in exception handling class and php built-in exception handling. Extends the PHP built-in exception handling class. php built-in exception handling is in the try code block. you need to use the throw statement to throw an exception object before you can jump to the catch code block for execution, extends the PHP built-in exception handling class in c and php built-in exception handling class.

In the try code block, you must use the throw statement to throw an exception object to jump to the catch code block for execution, and capture and use this exception class object in the catch code block. Although the built-in Exception handling class Exception provided in PHP already has very good features, in some cases, it may need to be extended to get more functions. Therefore, you can use a custom exception handling class to extend the PHP built-in exception handling class. The following code describes which attributes and methods are accessible and inherited in the built-in exception handling class:

12345678910111213141516171819 class Exception{protected $message = 'Unknown exception'; // Exception informationprotected $code = 0; // Custom exception codeprotected $file; // File name with exceptionprotected $line; // The line number of the code that has encountered an exception function __construct($message =null,$code=0){}final function getMessage(){} // Return exception informationfinal function getCode(){} // Return the exception codefinal function getFile(){} // Return the abnormal file namefinal function getLine(){} // Return the abnormal code line numberfinal function getTrace(){} // Backtrace () arrayfinal function getTraceAsString(){} // GetTrace () information formatted as a string // Reload-able method to output stringsfunction __toString(){}}?>

The above code only describes the structure of the built-in Exception handling function Exception class. it is not a practical usable code. If you use a custom class as the Exception handling class, it must be a subclass of the extended built-in Exception handling class Exception. non-Exception classes cannot be used as Exception handling classes. If you re-define the constructor when extending the built-in exception handling class inititon, we recommend that you call parent: construct () to check whether all variables have been assigned values. When an object needs to output a string, you can reload _ toString () and customize the output style. In a custom subclass, you can directly use the built-in Exception to handle all member attributes in the Exception class, but you cannot rewrite the member methods inherited from the parent class, because most public methods of this class are final.
It is very simple to create a custom Exception handler, which is the same as the Declaration method of the traditional class, but this class must be an extension of the built-in Exception handling class Exception. When an exception occurs in PHP, you can use a method in the custom exception class to handle it. Create a custom MyException class that inherits all the attributes of the built-in Exception handling class Exception and adds a custom method to it. The code and application are as follows:

123456789101112131415161718192021222324252627282930 // The titrator is an exception handling class, but must be a subclass of the extended exception handling class.class MyException extends Exception{// Redefine the constructor to change the first parameter message to a required attributepublic function __construct($message,$code=0){// Define your own code here// We recommend that you call parent: construct () to check whether all variables have been assigned values.parent::__construct($message,$code);}// Override the parent class method to customize the output style of the stringpublic function __toString(){return __CLASS__.":[".$this->code."]:".$this->message."
"
;}// Customize a processing method for this exceptionpublic function customFunction(){echo "Handle exceptions of this type by custom method
"
;}} try{$error='Allow throwing this error'; throw new MyException($error); // Create a processing object for a custom exception and throw it through the throw statementecho 'Never executed'; // From here, the code in the try code block will not be executed again}catch(MyException $e){ // Capture custom exception objectsecho 'Capture exception :'.$e; // Output the captured exception message$e->customFunction(); // Handle exceptions using methods in custom exception objects} echo 'Hi'; // The program does not crash and continues to run down?>

In the custom mypolicition class, use the constructor in the parent class to check whether all variables have been assigned values. Besides, the _ toString () method in the parent class is overloaded to output the custom exception handling class. there is no big difference in usage, but in the custom exception handling class, you can call a special method for handling specific exceptions.

> Fixed link: http://php.ncong.com/php_course/wrong/yichangchulilei.html

> For reprinted information, please note: ncong php was published in ncong PHP learning tutorial on September 10, August 06, 2014.


PHP exception handling problems

I have discussed this issue with my colleagues a few days ago. Let me explain

For example, if you call try catch and the array exceeds the standard, how does the program know that the array exceeds the standard? it must be reported by the array class.
In the array class, it must be throw. you can catch it and get the message. the array exceeds the standard. However, if the array class is caught directly, no exception will occur! In this way, even if you call the array, your own catch will fail, because no one throws an exception.

Others' answers are too Official. please accept my answers.

PHP custom exception processor usage

The PHP custom exception processor we introduced is the built-in exception_uncaught_handler () function of PHP. This function can be used to set custom exception handling functions to handle exceptions not captured by trycatch blocks.
The following four sections of code show my simple application (non-production environment) in the waylife project, which is neither robust nor beautifying, but the SNS project has died.
1. hierarchical relationship of exception classes:
ClassNotFoundExceptionextendsException {}
ClassInputExceptionextendsException {}
ClassDBExceptionextendsException {}
2. configure a processor that does not capture exceptions:
Functionexception_uncaught_handler (Exception $ e ){
Header ('content-type: text/html; charset = utf-8 '); if ($ einstanceofNotFoundException) exit ($ e-
GetMessage ());
Elseif ($ einstanceofDBException) exit ($ e-
GetMessage (); elseexit ($ e-
GetMessage ();} set_exception_handler ('exception _ uncaught_handler ');
3. in the sky of source code for database connection
, Manually throws a DBException exception but does not use trycatch for capture and processing. this exception will be handled by the PHP custom exception processor exception_uncaught_handler (): $ this-resConn = mysql_connect
($ CONFIGS ['DB _ host'], $ CONFIGS ['DB _ user'], $ CONFIGS ['DB _ pwd']); if (false = is_resource ($ this-resConn) thrownewDBException ('database connection failed. '. Mysql_error ($ this-resConn); 4. Business logic:
If (0! = Strcmp ($ curAlbum-
Interest_id, $ it ))
ThrownewNotFoundException ('sorry, the album you accessed does not exist ');

In the try code block, you must use the throw statement to throw an exception object to jump to the catch code block for execution...

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.