Exception and error parsing in PHP

Source: Internet
Author: User
Tags deprecated ereg parse error php error php exception handling throw exception hosting
PHP error is a problem in the PHP program itself, generally by illegal syntax, environmental problems caused by the compiler can not be checked or even unable to run the situation. PHP exceptions are typically unexpected and different from normal processes in business logic, not syntax errors. This article describes the exception and error in PHP data, the need for friends can refer to.

I. Exceptions and Errors

An exception is a situation in which a program does not meet expectations and is different from the normal process. Errors are a matter of their own, an illegal syntax or environmental problem that causes the compiler to fail to check that the settings cannot run.

Since PHP was the first to have no exception processing, and later in order to enter the enterprise-level development, imitate Java and other languages, introduced the exception. Any errors encountered in PHP will trigger an error instead of throwing an exception (in some cases, throwing an error and an exception). Once PHP encounters abnormal code, in most cases, it throws the error directly, not the exception.

PHP only uses Try...catch to catch exceptions after you throw an exception (in general, some exceptions can be automatically captured).

Exceptions are typically used in PHP in the following scenarios:

1. Pessimistic projections of the procedure: If you believe your code cannot handle all foreseeable situations, unforeseen circumstances.

2. The needs of the program and the attention to the business: if the consistency of the data requirements are high, you can use Try...catch to minimize the disruption of the logical interrupt, and after remedial processing, does not affect the integrity of the business logic.

3. Language-level robustness requirements: by precisely controlling the run-time process, in the case of a program interruption, the foreseeable use of try...catch to narrow the range of possible errors, timely catch the anomalies and make corresponding remediation.

Second, how to see the exception of PHP

History causes PHP exception handling is insufficient, in most cases, cannot automatically throw an exception, you must use If...else first judgment, and then manually throw the exception.

The meaning of manually throwing an exception is not great, because it means that the error has been fully anticipated in the code. It also allows you to be disoriented in complex logic judgments and processes. The real merit of losing an exception.

So is there a better way to throw exceptions? Yes, that's a combination of use errors

Iii. Errors in PHP

An error is a condition that causes the script to run abnormally.

The main error levels in PHP are as follows:

1. Deprecated: The lowest level of error, which means "not recommended, not recommended." For example, a regular function that uses the Ereg series in PHP 5 will appear. Such errors are generally caused by the use of deprecated, outdated functions or grammars. does not affect the normal operation of the program, but recommended remediation.

2. Notice: generally refers to the existence of inappropriate grammar in the place. This error is reported if a variable is used but not defined. does not affect the normal process of the program.

3. Warning: Higher-level errors, which can occur in a very inappropriate syntax, such as a function parameter mismatch. will result in unexpected results and need to modify the code.

4. Fetal error: Fatal errors, which directly cause the program to terminate operation. This type of error must be modified.

5. Prase Error: Parsing errors, the above are run-time errors, this error will be thrown before running.

In PHP, there are a total of 16 error levels, but the main one is the top several.

error.php

$data = ' 2012-12-20 ', if (Ereg ([0-9]{4})-([0-9]{1,2})-([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 executes, there will be four error levels, if you cannot fully see, you need to go to modify your INI config file error display level to E_all

Iv. Custom Error handlers

You can use set_error_handler() functions to host error handlers, and you can customize the wrong processing process yourself.

If you want to cancel hosting, you can use it on the same page restore_error_handler() to cancel hosting.

If you want to throw an error yourself, you can use a trigger_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];

Executing the above code, you can see that the error message is output by our custom handler, completely bypassing the system's handler.

If the error occurs before the custom handler, our custom error handler is not called, so the error handler should be defined first.

Of course not all error levels can be managed with set_error_handler, such as Eerror, Eparse, ecodewarning, Ecompileerror, ecompilewarning, and e_strict parts. These error messages are displayed in the original way or are not realistic.

PHP sees 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 Yes, throw exception manually 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 approach also has its own advantages and disadvantages:

Disadvantage: You must rely on the programmer to control the handling of the exception, for the exception of the area, sensitive areas, if the programmer does not handle, will lead to inconsistent business data issues.

Pros: You can obtain contextual information about the runtime of the program for targeted remediation.

fetal errorSuch errors cannot be captured, nor can the process be resumed after they occur, but a function may be used to trigger a function when the register_shutdown_function() program terminates or die, giving the program a brief resurrection. In PhP4, destructors are not supported and are often used to simulate the implementation of destructors.

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, resulting in failure echo ' must terminate ';

Parse error level errors, in addition to modifying the INI file, write error messages to the log, nothing can be done.

Summary

Errors and exceptions in PHP are two different concepts, which fundamentally result in PHP exceptions and errors that differ from other languages. In Java, the exception is the only way to report errors. In the final analysis, the difference between the two is different from the understanding of the anomaly. The majority of PHP exceptions are manually thrown in some way to capture them. is a semi-automatic exception handling mechanism.

Regardless of the error or exception, you can use the handler to take over the system's existing processing mechanism.

The above is the whole content of this article, I hope that everyone's study has helped.


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.