Php exception handling mechanism and error handling

Source: Internet
Author: User
Tags php exception handling
In php, the most commonly used error mechanism trycatch {} is used to handle errors that can be captured through instant noodles, however, in php, error checking and disabling are also provided. you can process the error in phpini or add error_display at the beginning of the file.

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:

  1. $ A = fopen('test.txt ', 'r ');
  2. // The file is opened without judgment. if the file does not exist, an error is returned.
  3. ?>

The correct statement should be as follows:

  1. If(file_exists('test.txt ')){
  2. Using fw.fopen('test.txt ', 'r ');
  3. // Close after use
  4. Fclose ($ f );
  5. }
  6. ?>

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

  1. If (! File_exists('aa.txt ')){
  2. Die ('file does not exist ');
  3. } Else {
  4. // Perform the operation
  5. }
  6. // If the die () is triggered, the echo is not executed here.
  7. Echo 'OK ';

Concise syntax:

  1. File_exits('aaa.txt ') or die ('file does not exist ');
  2. 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:

  1. Function error_function ($ error_level, $ error_message, $ error_file, $ error_line, $ error_context)
  2. // After creation, you need to rewrite set_error_handler (); function
  3. 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:

  1. 'If ($ age> 120 ){
  2. Echo 'age error'; exit ();
  3. }
  4. Trigger:
  5. 'If ($ age> 120 ){
  6. // Trigger_error ('error information' [, 'error level']); the error level is optional and is used to define the error level.
  7. // User-defined levels include E_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE.
  8. Trigger_error ('Age error'); // The default error handling method of the called System. you can also use a custom processor.
  9. }
  10. // Custom processor, same as above
  11. Function myerror ($ error_level, $ error_message ){
  12. Echo 'error text ';
  13. }
  14. // At the same time, you need to change the default processing function of the system.
  15. 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 generally the following: e_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE]
  16. // Now trigger_error can be used to customize the error handling function.

Exercise questions:

  1. Date_default_timezone_set ('prc ');
  2. Function myerror ($ error_level, $ error_message ){
  3. $ Info = "error code: $ error_leveln ";
  4. $ Info. = "error message: $ error_messagen ";
  5. $ Info. = 'Occurrence Time: '. date ('Y-m-d H: I: s ');
  6. Using filename='aa.txt ';
  7. If (! $ Fp = fopen ($ filename, 'A ')){
  8. 'File creation '. $ filename. 'failed ';
  9. }
  10. If (is_writeable ($ filename )){
  11. If (! Fwrite ($ fp, $ info )){
  12. Echo 'failed to write the file ';
  13. } Else {
  14. Echo 'error message recorded successfully ';
  15. }
  16. Fclose ($ fp );
  17. } Else {
  18. Echo 'file'. $ filename. 'unwriteable ';
  19. }
  20. Exit ();
  21. }
  22. Set_error_handler ('myerror', E_WARNING );
  23. Using fpw.fopen('aaa.txt ', 'r ');
  24. ?>

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

  1. Try {
  2. // Code that may contain errors or exceptions
  3. // Catch Exception is an Exception class defined by php
  4. } Catch (Exception $ e ){
  5. // Handle the exception. method:
  6. // 1. handle it by yourself
  7. // 2. if it is not processed, throw it again
  8. }

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. // Create a function that can throw an exception
  2. Function checkNum ($ number ){
  3. If ($ number> 1 ){
  4. Throw new Exception ("Value must be 1 or below ");
  5. }
  6. Return true;
  7. }
  8. // Trigger an exception in the try code block
  9. Try {
  10. CheckNum (2 );
  11. // If an exception is thrown, the following line of code will not be output
  12. Echo 'If you see this, the number is 1 or below ';
  13. } Catch (Exception $ e ){
  14. // Capture exceptions
  15. Echo 'message: '. $ e-> getMessage ();
  16. }
  17. ?>

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.

  1. // Set a top-level exception processor
  2. The code is as follows:
  3. Function myexception ($ e ){
  4. Echo 'this is top exception ';
  5. } // Modify the default exception processor
  6. Set_exception_handler ("myexception ");
  7. Try {
  8. $ I = 5;
  9. If ($ I <10 ){
  10. Throw new exception ('$ I must greater than 10 ');
  11. }
  12. } Catch (Exception $ e ){
  13. // Handle exceptions
  14. Echo $ e-> getMessage ().'
    ';
  15. // Continue to throw if the exception is not handled
  16. Throw new exception ('errorinfo'); // you can use throw $ e to retain the original error message;
  17. }

Create a custom exception class

  1. Class customException extends Exception {
  2. Public function errorMessage (){
  3. // Error message $ errorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ().':'. $ This-> getMessage ().'Is not a valid E-Mail address '; return $ errorMsg;
  4. }
  5. }
  6. // Use
  7. Try {
  8. Throw new customException ('error message ');
  9. } Catch (customException $ e ){
  10. Echo $ e-> errorMsg ();
  11. }

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

  1. Try {
  2. $ I = 5;
  3. If ($ I> 0 ){
  4. Throw new customException ('error message'); // use a custom exception class for processing
  5. } If ($ I <-10 ){
  6. Throw new exception ('error2 '); // use the default system exception
  7. }
  8. } Catch (customException $ e ){
  9. Echo $ e-> getMessage ();
  10. } Catch (Exception $ e1 ){
  11. Echo $ e1-> getMessage ();
  12. }

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.

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.