PHP error handling and Exception Handling notes

Source: Internet
Author: User
Tags php error
Summarize PHP error handling for new users. PHP provides error handling and logging functions. these functions allow you to define your own error handling rules and how to modify error records. in this way, you can modify and enhance the error output information as needed to meet your actual needs. with the logging function, you can directly send information

Summarize PHP error handling for new users. PHP provides error handling and logging functions. these functions allow you to define your own error handling rules and how to modify error records. in this way, you can modify and enhance the error output information as needed to meet your actual needs. with the logging function, you can directly send information

Summarize PHP error handling for new users.

PHP provides error handling and logging functions. these functions allow you to define your own error handling rules and how to modify error records. in this way, you can modify and enhance the error output information as needed to meet your actual needs.

With the logging function, you can directly send information to other log servers, or to a specified email address (or sent through the mail gateway), or to operating system logs, in this way, you can choose to record and monitor the most important part of your applications and websites.

The error report function allows you to customize the error feedback level and type. It can be a simple prompt or a custom function for processing and returning information.


Why use error handling?

• User-friendly website Error
• Better error avoidance, debugging, and fixing
• Avoid some security risks
• Better program robustness
•......
1. Simplest error handling-die ()
When an error is expected, we will stop running. For example, when you connect to a database

Mysql_connect ('localhost', www.111cn.net, '123 ')
Or die ('database connection error: '. mysql_error ());

However, simply terminating the script is not always the proper method.

2. Custom errors and error triggers
We create a special function for error handling. After setting it using the set_error_handler function, we can call this function when an error occurs in PHP.
Define the parameters of the error handling function

Parameters Description
Error_level Required. Specifies the error report level for user-defined errors. It must be a value.
See the following table: Error Report level.
Error_message Required. Specifies an error message for a user-defined error.
Error_file Optional. Specifies the file name in which the error occurs.
Error_line Optional. Specifies the row number of the error.
Error_context Optional. Define an array that contains each variable and their values when an error occurs.

Variable reservation

Value Constant Description Remarks
1 E_ERROR(Integer) Fatal runtime error. Such errors are usually irrecoverable, such as problems caused by memory allocation. The consequence is that the script stops running.
2 E_WARNING(Integer) Run-Time Warning (non-fatal error ). Only prompts are provided, but the script does not stop running.
4 E_PARSE(Integer) Syntax Parsing error during compilation. Parsing errors are only generated by the analyzer.
8 E_NOTICE(Integer) Runtime notification. Indicates that the script may be incorrectly displayed, but similar notifications may occur in scripts that can run normally.
16 E_CORE_ERROR(Integer) A fatal error occurs during PHP initialization and startup. This error is similarE_ERRORBut it is produced by the core of the PHP engine. Since PHP 4
32 E_CORE_WARNING(Integer) Warning during PHP initialization startup (non-fatal error ). SimilarE_WARNINGBut it is produced by the core of the PHP engine. Since PHP 4
64 E_COMPILE_ERROR(Integer) Fatal compilation error. SimilarE_ERRORBut it is generated by the Zend script engine. Since PHP 4
128 E_COMPILE_WARNING(Integer) Compile-time warning (non-fatal error ). SimilarE_WARNINGBut it is generated by the Zend script engine. Since PHP 4
256 E_USER_ERROR(Integer) Error message generated by the user. SimilarE_ERRORBut it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
512 E_USER_WARNING(Integer) User-generated warning information. SimilarE_WARNINGBut it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
1024 E_USER_NOTICE(Integer) User-generated notification information. SimilarE_NOTICEBut it is generated by the user using the PHP function trigger_error () in the code. Since PHP 4
2048 E_STRICT(Integer) Enable PHP code modification suggestions to ensure the best code interoperability and forward compatibility. Since PHP 5
4096 E_RECOVERABLE_ERROR(Integer) Possible fatal errors. It indicates that a potentially dangerous error has occurred, but it has not caused the PHP engine to be unstable. If the error is not captured by the custom handle (see set_error_handler (),E_ERRORThe script stops running. Since PHP 5.2.0
8192 E_DEPRECATED(Integer) Runtime notification. When enabled, a warning will be given to code that may not work properly in future versions. Since PHP 5.3.0
16384 E_USER_DEPRECATED(Integer) User-generated warning information. SimilarE_DEPRECATEDBut it is generated by the user using the PHP function trigger_error () in the code. Since PHP 5.3.0
30719 E_ALL(Integer) E_STRICTAll outgoing errors and warnings. 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previusly


(Level E_ERROR and E_USER_ERROR cannot be caught by the custom error handling function) the User-Defined error function cannot catch the fatal error information, because the script stops immediately when a fatal running error occurs.

Trigger Error
The location where the user inputs data in the script. It is useful to trigger errors when the user inputs are invalid. In PHP, this task is completed by trigger_error.

You can trigger an error at any position in the script. By adding the second parameter, you can specify the trigger error level.

Possible error types:
• E_USER_ERROR-fatal User-Generated run-time error. The error cannot be recovered. Script Execution is interrupted.
• E_USER_WARNING-run-time Warning generated by non-fatal users. Script execution is not interrupted.
• E_USER_NOTICE-default. User-Generated run-time notification. A possible error is found in the script, or it may occur when the script runs normally.
For example:

1
2
Trigger_error ("error", E_USER_WARNING );
// Output Warning: error message in xxxx
3. Error Report

By default, according to The error_log configuration in php. ini, PHP sends an error record to the server's error record system or file.
By using the error_log () function, you can send error records to specified files or remote destinations. For example, sending an error message to your mailbox is a good way.

For more error handling documentation, see: http://www.php.net/manual/zh/book.errorfunc.php

4. Exception Handling

When an exception is thrown, the subsequent code will not continue to be executed, and PHP will try to find the matching "catch" code block.

If the exception is not captured and set_exception_handler () is not used for corresponding processing, a serious (fatal) error will occur ), and output the "Uncaught Exception" (No Exception is captured) error message.

The processing process should include:

1. try-the abnormal function should be located in the "try" code block. If no exception is triggered, the Code continues as usual. However, if an exception is triggered, an exception is thrown.
2. throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
3. the catch-"catch" code block captures exceptions and creates an object containing exception information.
Throw an exception again.

Sometimes, when an exception is thrown, you may want to handle it in a different way than the standard. You can throw an exception again in a "catch" code block.

The script should hide system errors from users. For programmers, system errors may be important, but users are not interested in them. To make it easier for users to use, you can throw an exception with user-friendly messages.

Abnormal rules

Code that requires exception handling should be placed in the try code block to capture potential exceptions.
Each try or throw code block must have at least one catch code block.
Multiple catch code blocks can capture different types of exceptions.
You can throw a (re-thrown) exception again in the catch code block in the try code block.

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.