Php exception handling mechanism and error handling

Source: Internet
Author: User
Tags php error php exception handling try catch
In php, the most commonly used error mechanism trycatch {} is used to handle errors that can be captured through instant noodles, however, in php, errors can be viewed and disabled in php. you can add an e... in php, the most common error mechanism we use is try catch {}, which can catch errors easily, however, in php, errors can be viewed and disabled in php. you can add error_display (0) at the beginning of the file in ini to avoid displaying errors.

The code is as follows:

 

The correct statement should be as follows:

 

I. PHP error handling methods A. simple die () statements;Equivalent to exit (); example:

If (! File_exists('aa.txt ') {die ('file does not exist');} else {// execute the operation} // if the preceding die () is triggered, echo 'OK' is not executed here ';

Concise syntax:

File_exits('aaa.txt ') or die ('file does not exist'); echo' OK ';

B. Custom errors and error triggers

1. Error Processor (custom error, usually used for syntax error handling). create a custom error function (processor). This function must be able to process at least two parameters (error_level and errormessage ), however, you can accept the syntax of up to five parameters (error_file, error_line, and error_context:

Function error_function ($ error_level, $ error_message, $ error_file, $ error_line, $ error_context) // after creation, you must rewrite set_error_handler (); function set_error_handler ('error _ function ', e_WARNING); // here error_function corresponds to the custom processor name created above, and the second parameter is the error level of the Custom Error Processor;

The error reporting level (you can understand). These error reporting levels are different types of errors that the error handling program aims to handle:

Value constant description

2 E_WARNING: non-fatal run-time error. Do not pause script execution.

8 E_NOTICE Run-time notification. an error may occur when the script runs normally.

256 E_USER_ERROR fatal user-generated error. This is similar to the E_ERROR set by the programmer using the PHP function trigger_error.

512 E_USER_WARNING non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error.

1024 E_USER_NOTICE user-generated notifications. This is similar to the E_NOTICE set by the programmer using the PHP function trigger_error.

4096 E_RECOVERABLE_ERROR: a fatal error that can be captured. Similar to E_ERROR, but can be captured by a user-defined handler. (See set_error_handler ())

8191 all E_ALL errors and warnings, except for the level E_STRICT (in PHP 6.0, E_STRICT is part of E_ALL)

2. error trigger (generally used to handle logical errors). requirement: for example, to receive an age, if the number is greater than 120, it is regarded as an error. the traditional method is as follows:

If ($ age> 120) {echo 'age error'; exit () ;}use trigger: if ($ age> 120) {// trigger_error ('error information '[, 'error level']); here the error level is optional, and the levels used to define the error // user-defined levels include the following: e_USER_WARNING, E_USER_ERROR, E_USER_NOTICE trigger_error ('Age error'); // The default error handling method of the called System. you can also use a custom processor} // custom processor, same as the above function myerror ($ error_level, $ error_message) {echo 'error text';} // At the same time, you need to change the default processing function set_error_handler ('myerror', E_USER_WARNING ); // same as above, the first parameter is the name of the custom function, and the second parameter is the error level. [the error level here is usually the following three types: e_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE // you can use the custom error handling function by using trigger_error.

Exercise questions:

 

C. error log

By default, according to the error_log configuration in php. ini, php sends error records to the server's error record system or file. You can use the error_log () function to send error records to files or remote destinations;

Syntax:

Error_log (error [, type, destination, headers])

The type part usually uses 3 to indicate appending an error message to the end of the file, instead of overwriting the original content.

Destination indicates the destination, that is, the stored file or remote destination.

For example, error_log ("$ error_info", 3, "errors.txt ");

II. PHP exception handling [key]

1. Basic syntax

Try {// code that may contain errors or exceptions // catch Exception is a php defined Exception class} catch (Exception $ e) {// handle the Exception. method: // 1. process it by yourself. // 2. throw it again if it is not processed}

2. the handler should include: Try-use abnormal functions should be located in the "try" code block. If no exception is triggered, the code continues as usual. However, if an exception is triggered, an exception is thrown.

Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"

The Catch-"catch" code block captures exceptions and creates an object containing exception information.

Let's trigger an exception:

 1) {throw new Exception ("Value must be 1 or below");} return true;} // trigger an Exception in the "try" code block try {checkNum (2 ); // If an Exception is thrown, the following line of code will not be output echo 'If you see this, the number is 1 or below';} catch (Exception $ e) {// capture the exception echo 'message :'. $ e-> getMessage () ;}?>

The above code will get an error like this: Message: Value must be 1 or below

Example: the code above throws an exception, captures it, creates a checkNum () function, and checks whether the number is greater than 1. If yes, an exception is thrown and the checkNum () function is called in the "try" code block.

An exception in the checkNum () function is thrown. the "catch" code block receives the exception and creates an object containing the exception information ($ e ), call $ e-> getMessage () from this exception object to output error messages from this exception. however, to follow the principle that "each throw must correspond to a catch, you can set a top-level exception processor to handle missed errors.

The set_exception_handler () function can be used to set user-defined functions for handling all uncaptured exceptions.

// Set a top-level exception processor code as follows: function myexception ($ e) {echo 'this is top exception';} // modify the default exception processor set_exception_handler ("myexception "); try {$ I = 5; if ($ I <10) {throw new exception ('$ I must greater than 10') ;}} catch (Exception $ e) {// handle exceptions echo $ e-> getMessage ().'
'; // If The exception is not handled, throw new exception ('errorinfo') is thrown. // you can use throw $ e to retain the original error message ;}

Create a custom exception class

Class customException extends Exception {public function errorMessage () {// error message $ errorMsg = 'Error on line '. $ this-> getLine (). 'In '. $ this-> getFile (). ':'. $ This-> getMessage ().'Is not a valid E-Mail address '; return $ errorMsg; }}// use try {throw new customException ('error message');} catch (customException $ e) {echo $ e-> errorMsg ();}

Multiple catch methods can be used to return error messages in different situations.

Try {$ I = 5; if ($ I> 0) {throw new customException ('error message '); // use a custom exception class for processing} if ($ I <-10) {throw new exception ('error2 '); // use the default system Exception handling} catch (customException $ e) {echo $ e-> getMessage ();} catch (Exception $ e1) {echo $ e1-> getMessage ();}

The catch handling error idea is that we often use php5 in development and will be added later. This function is not available in php4, and many functions will be more comprehensive as php continues to work.

Permanent link:

Reprint at will! Include the article address.

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.