Php exception handling and error handling methods-php Tutorial

Source: Internet
Author: User
Tags php exception handling
Summary of php exception handling and error handling methods

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

Correct syntax:

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

I. three methods for PHP error handling I. simple die () statement; 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 ';

Method 2: custom errors and error triggers

1. Error Processor (custom error, usually used for syntax error handling) to 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 a maximum of five parameters (error_file, error_line, and error_context). Syntax: function error_function ($ error_level, $ error_message, $ error_file, $ error_line, $ error_context) // after creation, you also need to rewrite set_error_handler (); function set_error_handler ('error _ function', E_WARNING); // here error_function corresponds to the custom processor name created above, the second parameter is the error level of the custom error processor, and the error report level (understanding)

These error reporting levels are different types of errors intended by the error handler: value constant description 2 E_WARNING non-fatal run-time errors. Do not pause script execution. 8 E_NOTICERun-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 E_ALL 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) requirements: for example, to receive an age, if the number is greater than 120, it is considered as a traditional method of error:

  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.

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 // you can use the custom error processing function by using trigger_error:

  1. Date_default_timezone_set ('prc ');
  2. Function myerror ($ error_level, $ error_message ){
  3. $ Info = "error code: $ error_level \ n ";
  4. $ Info. = "error message: $ error_message \ n ";
  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. ?>

Method 3: The error log is configured according to error_log in php. ini by default, and 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 section usually uses 3 to indicate appending an error message to the end of the file, instead of overwriting the original content destination to indicate the destination, that is, the stored file or remote destination such as error_log(%%error_info%,3,%errors.txt ");

II. PHP exception handling

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" Catch-"catch" code block to capture exceptions and create an object containing exception information.

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 report the following error: Message: Value must be 1 or below

Explanation:

The above code throws an exception and captures it:

Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown. Call the checkNum () function in the "try" code block. An exception in the checkNum () function is thrown a "catch" code block to receive the exception and create an object containing the exception information ($ e ). By calling $ e-> getMessage () from this exception object, an error message from this exception is output. 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. Function myexception ($ e ){
  3. Echo 'this is top exception ';
  4. } // Modify the default exception processor
  5. Set_exception_handler ("myexception ");
  6. Try {
  7. $ I = 5;
  8. If ($ I <10 ){
  9. Throw new exception ('$ I must greater than 10 ');
  10. }

  11. } Catch (Exception $ e ){

  12. // Handle exceptions
  13. Echo $ e-> getMessage ().'
    ';
  14. // Continue to throw if the exception is not handled
  15. Throw new exception ('errorinfo'); // you can use throw $ e to retain the original error message;
  16. }

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
  4. Address '; return $ errorMsg;
  5. }
  6. }
  7. // Use
  8. Try {
  9. Throw new customException ('error message ');
  10. } Catch (customException $ e ){
  11. Echo $ e-> errorMsg ();
  12. }

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. }

Rules for exception use: 1. Place the code that requires exception handling in the try code block to capture potential exceptions. 2. each try or throw code block must have at least one catch code block. 3. multiple catch code blocks can capture different types of exceptions. 4. you can throw a (re-thrown) exception again in the catch code block in the try code.

Remember one sentence: If an exception is thrown, you must capture it.

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.