Error handling and exception handling mechanism in PHP _php techniques

Source: Internet
Author: User
Tags exception handling getmessage php error php exception handling
Cases:
Copy Code code as follows:

<?php
$a = fopen (' test.txt ', ' R ');
There is no decision on the file to open, if the file does not exist will be an error
?>

The correct wording should read as follows:
Copy Code code as follows:

<?php
if (file_exists (' Test.txt ')) {
$f =fopen (' Test.txt ', ' R ');
Close after use
Fclose ($f);
}
?>

One, PHP error handling three ways A, simple die () statement;
Equivalent to exit ();
Cases:
Copy Code code as follows:

if (!file_exists (' Aa.txt ')) {
Die (' File not present ');
} else {
Perform an action
}
If the above die () is triggered, then the echo is not executed here
echo ' OK ';

Concise wording:
Copy Code code as follows:

File_exits (' aaa.txt ') or Die (' file does not exist ');
echo ' OK ';

B, custom errors and error triggers

1, error processor (custom error, generally used for syntax error handling)
Create a custom error function (processor) that must have the ability to handle at least two parameters (Error_level and errormessage), but can accept up to five parameters (Error_file, Error_line, Error_context)
Grammar:
Copy Code code as follows:

function Error_function ($error _level, $error _message, $error _file, $error _line, $error _context)
You will also need to overwrite Set_error_handler () after 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 for using a custom error processor;

Error Reporting level (understood)

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

value Constants Description
2 E_warning Non-fatal run-time error. Script execution is not paused.
8 E_notice

Run-time notice.

The script found that an error might occur, but it may also occur when the script is running correctly.

256 E_user_error Fatal user-generated error. This is similar to the e_error that programmers use PHP function Trigger_error () settings.
512 E_user_warning A non-fatal user-generated warning. This is similar to the e_warning that programmers use PHP function Trigger_error () settings.
1024 E_user_notice User-generated notifications. This is similar to the e_notice that programmers use PHP function Trigger_error () settings.
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 for level e_strict.

(In PHP 6.0,e_strict is part of E_all)


2. Error triggers (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 Code code as follows:

if ($age >120) {
Echo ' age error '; exit ();
}

To use triggers:
Copy Code code as follows:

if ($age >120) {
Trigger_error (' Error message ' [, ' Error level ']) where the error level is optional, 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 system default error handling that is invoked, and we can also use a custom processor
}
Custom processor, same as above
function Myerror ($error _level, $error _message) {
Echo ' Error text ';
}
Also need to change the system default handler function
Set_error_handler (' Myerror ', e_user_warning); The first argument is the name of the custom function, and the second is the error level. The error level here is usually the following three: E_user_warning, E_user _error, E_user_notice "
Now you can use Trigger_error to work with custom error-handling functions.

Exercises:
Copy Code code as follows:

<?php
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 ' successfully logged error message ';
}
Fclose ($FP);
} else {
echo ' file '. $filename. ' Not written ';
}
Exit ();
}
Set_error_handler (' Myerror ', e_warning);
$fp =fopen (' Aaa.txt ', ' R ');
?>

C, error log
By default, according to the Error_log configuration in php.ini, PHP sends an error record to the server's error-recording system or file. You can send error records to a file or to a remote destination by using the Error_log () function;
Grammar:
Error_log (Error[,type,destination,headers])
The type section is typically 3, which means appending an error message after the file without overwriting the original
Destination represents a destination, a file or remote destination that is stored
such as: Error_log ("$error _info", 3, "errors.txt");
Second, PHP exception handling "Focus"
1. Basic grammar
Copy Code code as follows:

try{
Code with errors or exceptions that may occur
Catch capture exception is an exception class that PHP has defined well
catch (Exception $e) {
For exception handling, methods:
1. Handle Yourself
2, does not handle, throws it again
}

2. The processing procedure shall include:
Try-The function that uses the exception should be in the "try" code block. If no exception is fired, the code continues to execute as usual. However, if the exception is triggered, an exception is thrown.
Throw-Here's how to trigger an exception. Each "throw" must correspond to at least one "catch"
Catch-"catch" blocks catch exceptions and create an object that contains exception information
Let's trigger an exception:
Copy Code code as follows:

<?php
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, the following line of code will not be output
Echo ' If you are here, the number is 1 or below ';
}catch (Exception $e) {
Catch exception
echo ' message: '. $e->getmessage ();
}
?>

The code above will get an error like this:
Message:value must be 1 or below
Example Explanation:
The code above 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 exception information.
Output an error message from this exception by calling $e->getmessage () from this exception object
However, to follow the "each throw must correspond to a catch" principle, you can set up a top-level exception handler to handle the missing error.
Set_exception_handler () function to set up a user-defined function that handles all not caught exceptions
Copy Code code as follows:

Set up 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 exceptions, continue to throw
throw new Exception (' ErrorInfo '); The original error message can also be retained with throw $e;
}

To create a custom exception class
Copy Code code as follows:

Class Customexception extends exception{
Public Function errormessage () {
The error message $ERRORMSG = ' Error on line '. $this->getline (). $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
Copy Code code as follows:

try{
$i = 5;
if ($i >0) {
throw new Customexception (' error message ');//Use custom exception class to handle
} 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
Code that requires exception handling should be placed inside the try code block to catch potential exceptions. Each try or throw code block must have at least one corresponding catch code block. Multiple catch blocks can be used to catch different kinds of exceptions. You can throw a (re-thrown) exception again in a catch code block within the try code. In short: If an exception is thrown, it must be caught.

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.