This article to share the content is to solve the problem of PHP error handling and exception handling mechanism, has a certain reference value, the need for friends can refer to
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
Cases:
<?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; }? >
First, PHP error handling three ways
A, simple die () statement;
Equivalent to exit ();
Cases:
if (!file_exists (' Aa.txt ')) {die (' file does not exist '),} else { //Perform operation}//if the above die () is triggered, then echo ' OK ' is not executed here;
Concise wording:
File_exits (' aaa.txt ') or Die (' File not present '); 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)
Grammar:
function Error_function ($error _level, $error _message, $error _file, $error _line, $error _context)//need to overwrite set_error after creation _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 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:
A Value constant describes 2 e_warning non-fatal run-time error. Script execution is not paused. 8 E_notice run-time Notice. The script discovers that an error may have occurred, but it may also occur when the script is running correctly. the E_user_error a fatal user-generated error. This is similar to the e_error that programmers use to set the PHP function Trigger_error (). + E_user_warning a 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 captured. 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 mistake
Traditional methods:
<?PHPIF ($age >) { echo ' age error '; Exit ();}? >
Using triggers:
<?PHPIF ($age >) { //trigger_error (' Error message ' [, ' Error level ']), here the error level is optional, the level of the error is defined //user-defined level contains the following three kinds: E_user _warning, E_user_error, E_user_notice trigger_error (' age error ');//This is the default error handling of the system being called, we can also use custom processor}/** * To customize the processor, Same as above */function Myerror ($error _level, $error _message) { echo ' error text ';}// also need to change the system default handler Set_error_ Handler (' Myerror ', e_user_warning); As above, the first parameter is the name of the custom function, the second is the error level "The error level here is usually the following three kinds: e_user_warning, E_user_error, E_user_notice"//now use Trigger_ You can use the custom error-handling function?>
Exercises:
<?phpdate_default_timezone_set (' PRC '); function Myerror ($error _level, $error _message) { $info = "Error Number: $error _ Level "; $info. = "error message: $error _message"; $info. = ' Occurrence time: '. Date (' y-m-d h:i:s '); $filename = ' aa.txt '; if (! $fp = fopen ($filename, ' a ')) { echo ' create file '. $filename. ' Failure '; } if (is_writeable ($filename)) { if (!fwrite ($FP, $info)) { echo ' failed to write to file '; } else { echo ' has successfully logged error message '; c12/>} fclose ($FP); } else { echo ' file '. $filename. ' Not writable '; } Exit ();} Set_error_handler (' Myerror ', e_warning); $fp = fopen (' aaa.txt ', ' R ');? >
C, error log
By default, PHP sends error records to the server's error logging system or file according to the Error_log configuration in php.ini. You can send error records to a file or remote destination by using the Error_log () function.
Grammar:
Error_log (error[, type, destination, headers])
The type section typically uses 3, which means that an error message is appended to the file without overwriting the original content destination represents the destination, that is, the stored file or remote destination
such as: Error_log ("$error _info", 3, "errors.txt");
Second, PHP exception handling "Focus"
1. Basic grammar
<?phptry { ///Error or exception code //catch capture Exception is PHP defined exception class} catch (Exception $e) { //For exception handling, method: //1, self-processing //2, do not process, can be thrown again throw new Exception (' xxx ');}? >
2. Processing procedures shall include:
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;
Throw-this specifies how the exception is triggered. Each "throw" must correspond to at least one "catch";
Catch-the "catch" code block catches the exception and creates an object containing the exception information;
Let's trigger an exception:
<
php/** * Create a function that throws an exception */function Checknum ($number) { if ($number > 1) { throw new Exception ("Value must be 1 o R below "); } return true;} Triggering an exception in the "try" code block try { checknum (2); If the exception is thrown, then 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 EC Ho ' Message: '. $e->getmessage ();}? >
The above code will get an error like this:
Message:value must be 1 or below
Example Explanation:
The above code throws an exception and captures it:
Create the Checknum () function, which detects if the number is greater than 1, and if so, throws an exception.
Call the Checknum () function in the "Try" code block.
The exception in the Checknum () function is thrown.
The catch code block receives the exception and creates an object ($e) that contains the exception information.
The error message from this exception is output 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.
<?php/** * Set a top-level exception handler */function myexception ($e) { echo ' This is top exception ';}//modify default exception handler Set_exception_hand Ler ("MyException"); try { $i = 5; if ($i <) { throw new Exception (' $i must greater than) }} catch (Exception $e) { //Handle exception echo $ E->getmessage (). ' <br/> '; Do not handle exceptions, continue to throw throw new Exception (' errorinfo ');//You can also keep the original error message with the throw $e;}? >
To create a custom exception class
<?phpclass Customexception extends Exception {public function errormessage () { $errorMsg = ' Error in 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->errormessage ();} ?>
You can use multiple catch to return error messages in different situations
<?phptry { $i = 5; if ($i > 0) { throw new customexception (' error message ');//Use custom exception class handling } if ($i < -10) { throw NE W 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.
In short: If an exception is thrown, it must be captured.