Error handling and exception handling mechanism analysis in PHP _php tutorial

Source: Internet
Author: User
Tags php error php exception handling
Cases:
Copy CodeThe code is as follows:
$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:
Copy CodeThe code is as follows:
if (file_exists (' Test.txt ')) {
$f =fopen (' Test.txt ', ' R ');
Close when you are finished using
Fclose ($f);
}
?>

One, PHP error handling of three ways A, simple die () statement;
Equivalent to exit ();
Cases:
Copy CodeThe code is as follows:
if (!file_exists (' Aa.txt ')) {
Die (' file does not exist ');
} else {
Perform actions
}
If the above die () is triggered, then ECHO is not executed here
echo ' OK ';

Concise wording:
Copy CodeThe code is as follows:
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:
Copy CodeThe code is as follows:
function Error_function ($error _level, $error _message, $error _file, $error _line, $error _context)
You will also need to overwrite Set_error_handler () when you create it;
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:

value Constants Description
2 E_warning A 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.

256 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 ().
512 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 ().
1024 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 mistake
Traditional methods:
Copy CodeThe code is as follows:
if ($age >120) {
Echo ' age error '; exit ();
}

Using triggers:
Copy CodeThe code is as follows:
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_notice
Trigger_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 ';
}
Also need to change the system default processing function
Set_error_handler (' Myerror ', e_user_warning);//with above, the first parameter is the name of the custom function, and the second is the error level "Here is usually the following three kinds of error levels: E_user_warning, E_user _error, E_user_notice "
You can now use the custom error-handling function with Trigger_error.

Exercises:
Copy CodeThe code is as follows:
Date_default_timezone_set (' PRC ');
function Myerror ($error _level, $error _message) {
$info = "Error number: $error _level\n";
$info. = "error message: $error _message\n";
$info. = ' Occurrence time: '. Date (' y-m-d h:i:s ');
$filename = ' aa.txt ';
if (! $fp =fopen ($filename, ' a ')) {
' Create file '. $filename. ' Failure ';
}
if (is_writeable ($filename)) {
if (!fwrite ($FP, $info)) {
Echo ' Write file failed ';
} else {
Echo ' has successfully logged error messages ';
}
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, 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
Copy CodeThe code is as follows:
try{
Code with errors or exceptions that may occur
Catch capture exception is a well-defined exception class for PHP
} catch (Exception $e) {
For exception handling, method:
1, self-treatment
2. Do not process, throw it again
}

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 an exception and creates an object that contains the exception information
Let's trigger an exception:
Copy CodeThe code is as follows:
To create a function that throws an exception
function Checknum ($number) {
if ($number >1) {
throw new Exception ("Value must be 1 or below");
}
return true;
}
To trigger an exception in a "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) {
Catching exceptions
Echo ' 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. It detects if the number is greater than 1. If it is, an exception is thrown.
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.
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
Copy CodeThe code is as follows:
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 (). '
';
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
Copy CodeThe code is as follows:
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 ();
}

You can use multiple catch to return error messages in different situations
Copy CodeThe code is as follows:
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. In short: If an exception is thrown, it must be captured.

http://www.bkjia.com/PHPjc/325500.html www.bkjia.com true http://www.bkjia.com/PHPjc/325500.html techarticle Example: Copy code code as follows: PHP $a = fopen (' test.txt ', ' r ');//There is no judgment on the file is opened, if the file does not exist will be an error? Then the correct wording should ...

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