Php errors and exceptions

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

Php errors and exceptions

This article mainly introduces exceptions and errors in php and shares them with you for your reference. Let's take a look at the details below:

I. Exceptions and errors

An exception occurs when the program is running and the process is different from the normal process. An error is a problem of its own. It is caused by an invalid syntax or environment problem that causes the compiler to fail to run by checking settings.

Php started with no exception handling. Later, it introduced exceptions in order to enter enterprise-level development and imitate java and other languages. Any errors in php will trigger an error instead of throwing an exception (in some cases, errors and exceptions will be thrown at the same time ). In most cases, PHP directly throws an error instead of an exception when encountering abnormal code.

Php can use try... catch to catch exceptions only after you throw an exception (in general, some exceptions can be automatically captured ).

In php, exceptions are usually used in the following scenarios:

1. pessimistic prediction of the program: If you think your code cannot handle all kinds of foreseeable and unpredictable situations one by one.

2. program needs and business concerns: if the data consistency requirements are high, you can use try... catch minimizes the damage caused by logical interruptions caused by exceptions and does not affect the integrity of business logic after remediation.

3. language-level Robustness Requirements: by precisely controlling the running process, you can use try to anticipate program interruptions... catch can narrow down the scope of possible errors, catch exceptions in a timely manner, and remedy them accordingly.

Ii. View php exceptions

Php Exception Handling due to historical causes is insufficient. In most cases, exceptions cannot be automatically thrown. You must use if... else to determine the cause and then throw an exception manually.

Manually throwing an exception does not make much sense, because it means that the error has been fully anticipated in the code. At the same time, this method also leaves you confused in complicated logic judgment and processing. This leads to the loss of the true advantages of exceptions.

Is there a better way to throw exceptions? Yes, that is, combined with usage errors

3. Errors in php

An error occurs when the script runs abnormally.

The main error levels in php are as follows:

1. deprecated: the lowest-level error, indicating "not recommended, not recommended ". For example, if you use the ereg series regular functions in php 5. This type of error is generally caused by the use of unrecommended, outdated functions or syntax. It does not affect the normal operation of the program, but it is recommended that you modify it.

2. notice: The syntax is usually inappropriate. This error is reported if a variable is used but not defined. The normal process of the program is not affected.

3. warning: a higher-level error occurs only when the syntax is inappropriate. For example, function parameters do not match. This will lead to unexpected results. You need to modify the code.

4. fetal error: a fatal error that causes the program to stop running. This type of error must be modified.

5. prase error: Syntax Parsing error. The preceding errors are runtime errors. This error will be thrown before running.

In php, there are a total of 16 error levels, but the main ones are the above.

Error. php

$ Data = '1970-12-20 '; if (ereg ("([0-9] {4})-([0-9] {2012 }) -([0-9] {1, 2}) ", $ data, $ regs) {echo" $ reg [3]. $ regs [2]. $ regs [1] ";}else {echo" Invalid data format: $ data ";}$ a = array ('O' => 2, 4, 6, 8 ); echo $ a [o]; $ result = array_sum ($ a, 3); echo func (); echo 'fatal error, will it be executed? '; // Echo 'highest-level error', $55;

After the above code is executed, there will be four error levels. If you cannot see it completely, you need to modify the error display level in your ini configuration file to E_ALL

4. custom error handling program

Availableset_error_handler()Function to host error handlers. You can customize the error handling process.

If you want to cancel hosting, you can userestore_error_handler()To cancel hosting.

If you want to throw an error, you can usetrigger_error()Function.

<? Php // custom error handler function customError ($ errno, $ errstr, $ errfile, $ errline) {echo "<B> error code: </B> [{$ errno}] {$ errstr} ", PHP_EOL; echo" error code line: {$ errline} file {$ errfile} ", PHP_EOL; echo "PHP version", PHP_VERSION, "(", PHP_ OS, ")", PHP_EOL;} set_error_handler ("customError", E_ALL | E_STRICT ); $ a = array ('O' => 2, 4, 6, 8); echo $ a [o];

After executing the above code, we can see that the error message is output by our custom processing program, completely bypassing the system processing program.

If an error occurs before the Custom Handler, the Custom Handler will not be called. Therefore, the error handler should be defined first.

Of course, not all error levels can be managed using set_error_handler, such as EERROR, EPARSE, ECODEWARNING, ECOMPILEERROR, ECOMPILEWARNING, and E_STRICT. These error messages are displayed in the original or unrealistic way.

PHP regards many exceptions as errors, so these "exceptions" can also be taken over using set_error_handler:

Function customError ($ errno, $ errstr, $ errfile, $ errline) {// custom error handling is: manually throw an Exception throw new Exception ($ errstr );} set_error_handler ('customerror', E_ALL | E_STRICT); try {$ a = 5/0;} catch (Exception $ e) {echo 'error message :', $ e-> getMessage ();}

Of course, this processing method also has its own advantages and disadvantages:

Disadvantages: You must rely on the programmer to control the handling of exceptions. for high-risk and sensitive areas of exceptions, if the programmer does not handle the exceptions well, it will lead to inconsistent business data.

Advantage: You can obtain the context information when the program is running for targeted remediation.

fetal errorSuch errors cannot be captured, and the process cannot be restored after they occur. However, you can useregister_shutdown_function()The function triggers a function when the program ends or die, bringing a short return to the program. Php4 does not support destructor. It is also often used to simulate Implementation of destructor.

Class Shutdown {public function stop () {if (error_get_laster () {print_r (error_get_laster ();} die ('Stop. ') ;}} register_shutdown_function (array (new Shutdown (), 'stop'); $ a = new a (); // fatal error, cause failure echo 'must terminate ';

For errors at the Parse error level, in addition to modifying the INI file, the error information is written to the log, and nothing can be done.

Summary

Errors and exceptions in php are two different concepts. This design fundamentally leads to php exceptions and errors that are different from other languages. The only reporting method for errors in java. In the end, the difference between the two is that they have different understandings of exceptions. Most php exceptions can be captured only by manually throwing them in some way. Is a semi-automated exception handling mechanism.

Whether it is an error or an exception, you can use handler to take over the existing processing mechanism of the system.

Well, the above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message, thank you for your support.

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.