An explanation of error handling and exception handling mechanisms in PHP

Source: Internet
Author: User
Tags php error php exception handling

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)

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:

tr>
constant description
2 e_warning 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 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_noticetrigger_error (' age error '); Here is the system default error handling method called, we can also use 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);//same 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 types: E_user_warning, E_user_error, E_user_notice "//now use Trigger_error to use custom error handlers?>

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 ' Write to file failed ';} else {echo ' has successfully logged error message ';} 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) {//exception handling, Method://1, self-processing//2, non-processing, Can throw throw new Exception (' xxx ') again;}? >

2. Processing procedures shall 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 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 or Belo W ");} 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 (Exc Eption $e) {//catch exception 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:

    1. Create the Checknum () function, which detects if the number is greater than 1, and if so, throws an exception.
    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. 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 the default exception handler Set_exception_handler ("MyException"); try {$i = 5;if ($i <) {throw new Exception (' $i must greater than 1 0 ');}} catch (Exception $e) {//Handles exception echo $e->getmessage (). ' <br/> ';//do not handle exception, 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 to process}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.

Extended reading:

Thinkphp Learning: The use of PHP error handling function Set_error_handler ()

Thinkphp Learning: The use of PHP exception handling function Set_exception_handler ()

Exception handling and error handling in PHP: Error_reporting,try-catch,trigger_error,set_error_handler,set_exception_handler,register_ Shutdown_function

An explanation of error handling and exception handling mechanisms 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.