Errors and exception handling in PHP

Source: Internet
Author: User

Error handling is an important part of writing PHP programs. If error detection code is missing from the program, it looks unprofessional and opens the door to security risks

Example: <?php $a = fopen (' test.txt ', ' R ');        There is no judgment on the file opened, if the file does not exist will be an error?> then the correct wording should be as follows: <?php if (file_exists (' Test.txt ')) {$f =fopen (' Test.txt ', ' R ');    Close Fclose ($f) after use;    }?>, PHP error handling three ways A, simple die () statement, equivalent to exit (); Example: if (!file_exists (' Aa.txt ')) {die (' file does not exist ');     } else {//Perform action}//If the above die () is triggered, then echo ' OK ' is not executed here;    Concise wording: file_exits (' aaa.txt ') or Die (' file does not exist '); echo ' OK '; B, custom errors and error triggers 1, error processor (custom error, commonly used for syntax error handling)Create a custom error function (processor) that must be capable of handling at least two parameters (Error_level and errormessage), but can accept up to five parameters (Error_file, error_line, error_context) syntax: function Error_function ($error _level, $error _message, $error _file, $error _line, $error _context)//must be rewritten after creation. Set_err Or_handler (); functionset_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 using the custom error handler;Error Reporting level (learn it)

These error reporting levels are different types of errors that the error handler is designed to handle:

e_warning
value constant description
2 Non-fatal run-time error. Script execution is not paused.
8 e_notice

Run-time notification. The

Script discovers that an error may have occurred, but it may also occur when the script is running correctly.

up e_user_error Fatal user-generated error. This is similar to the e_error that programmers use to set the PHP function Trigger_error ().
up e_user_warning non-fatal user-generated warning. This is similar to the e_warning that programmers use to set the PHP function Trigger_error ().
1024x768 e_user_notice User-generated notifications. This is similar to the e_notice that programmers use to set the PHP function Trigger_error ().
4096 e_recoverable_error A fatal error that can be caught. Similar to E_error, but can be captured by user-defined handlers. (see Set_error_handler ())
8191 e_all

All errors and warnings except level e_strict.

(in PHP 6.0,e_strict is part of E_all)

 

2. Error trigger (typically used to handle logical errors)
requirements: For example to receive an age, if the number is greater than 120, it is considered a wrong traditional method:
if ($age >120) {
echo ' age error '; exit ();
}
Use trigger: if ($age >120) {//trigger_error (' error message ' [, ' Error level ']), where the error level is optional and is used to define the level of the error// User-defined levels include the following three types: E_user_warning, E_user_error, E_user_noticetrigger_error (' age error ');//This is the default error handling of the system being called, we can also use the custom processor}//Custom processor, same as above function Myerror ($error _level, $error _message) {echo ' error text '; }//need to change the system default handler function Set_error_handler (' Myerror ', e_user_warning);//with above, the first parameter is the name of the custom function, the second is the wrong one The error level "Here is usually the following three types of errors: e_user_warning, E_user_error, E_user_notice"//now use the custom error-handling function with the trigger_error to do the exercises:
1 <?php 2     date_default_timezone_set (' PRC '); 3     function Myerror ($error _level, $error _message) {4         $info = "Error number: $error _level\n"; 5         $info. = "error message: $error _message\n"; 6         $info. = ' time taken: '. Date (' y-m-d h:i:s '); 7         $filename = ' aa.txt '; 8         if (! $fp =fopen ($filename, ' a ')) {9             ' create file '. $filename. ' Failed ';         }11         if (is_writeable ($filename)) {[             !fwrite ($FP, $info)] {                 echo ' write file failed ';             else {                 echo ' has successfully logged error messages ';             }17                         fclose ($fp); '         else {             echo ' file '. $filename. ' Not writable ';         }21         exit ();     }23     set_error_handler (' Myerror ', e_warning);     $fp =fopen (' Aaa.txt ', ' R ');?>
C, error log       default based on Error_log configuration in php.ini, PHP sends error records to the server's error logging system or file. You can send error records to a file or remote destination by using the Error_log () function;        syntax:          &NBSP;&NBSP;ERROR_ Log (Error[,type,destination,headers])          Type section typically uses 3 to append an error message after the file without overwriting the original content         Destination represents the destination, which is the stored file or remote destination         such as: Error_log ("$error _info", 3, "Errors.txt ");  second, PHP exception handling" Focus " 1, basic grammar         try{           // Code that may appear error or exception            //catch capture  exception is PHP's defined exception class        } catch (Exception $e) {           //exception handling, method:               //1, self-processing                //2, do not process, re-throw it        }2, processing processing program should include:
    1. Try -the function that uses the exception should be in the "try" code block. If no exception is triggered, the code will continue to execute as usual. However, if an exception is triggered, an exception is thrown.
    2. Throw-this specifies how the exception is triggered. Each "throw" must correspond to at least one "catch"
    3. Catch-the "catch" code block catches an exception and creates an object that contains the exception information

Let's trigger an exception:

1 <?php 2//Create a function that throws an exception 3 functions Checknum ($number) {4     if ($number >1) {5         throw new Exception ("Value must be 1 or below "); 6     } 7     return true; 8} 9 10//Trigger exception in "Try" code block try{12     checknum (2);     //If the 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) {     //catch Exception     "Echo ' Message: '. $e->ge Tmessage ()}19?>

The above code will get an error like this:

Example Explanation:

The above code throws an exception and captures it:

    1. Create the Checknum () function. It detects if the number is greater than 1. If it is, an exception is thrown.
    2. Call the Checknum () function in the "Try" code block.
    3. The exception in the Checknum () function is thrown
    4. The catch code block receives the exception and creates an object ($e) that contains the exception information.
    5. Output the error message from this exception by calling $e->getmessage () from this exception object

However, to follow the principle that each throw must correspond to a catch, you can set up a top-level exception handler to handle the missing error.

The Set_exception_handler () function sets a user-defined function to handle all uncaught exceptions

Set a top-level exception handler

function MyException ($e) {

Echo ' This is top exception ';

}//Modify the default exception handler

Set_exception_handler ("MyException");

try{

$i = 5;

if ($i <10) {

throw new Exception (' $i must greater than 10 ');

}

}catch (Exception $e) {

Handling Exceptions

echo $e->getmessage (). ' <br/> ';

Do not handle exception, continue to throw

throw new Exception (' ErrorInfo '); You can also use the throw $e to retain the original error message;

}

To create a custom exception class

Class Customexception extends exception{

Public Function errormessage () {

Error message $ERRORMSG = ' Error on line '. $this->getline (). ' In '. $this->getfile (). ': <b> '. $this GetMessage (). ' </b> is not a valid e-mail address '; return $ERRORMSG;

}

}

Use

try{

throw new Customexception (' error message ');

}catch (Customexception $e) {

echo $e->errormsg ();

}

You can use multiple catch to return error messages in different situations

try{

$i = 5;

if ($i >0) {

throw new Customexception (' error message ');//Use custom exception class handling

} if ($i <-10) {

throw new Exception (' Error2 ');//Use system default exception handling

}

}catch (Customexception $e) {

echo $e->getmessage ();

}catch (Exception $e 1) {

echo $e 1->getmessage ();

}

Rules for exceptions
    • The code that requires exception handling should be placed inside a try code block to catch a potential exception.
    • Each try or throw code block must have at least one corresponding catch code block.
    • You can use multiple catch blocks to catch different kinds of exceptions.
    • You can throw (re-thrown) exceptions again in the catch code block within the try code.

Errors and exception handling in PHP

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.