_php tutorial on Understanding the anomaly mechanism in PHP

Source: Internet
Author: User
Tags log log php books php error php exception handling throw exception
PHP anomaly mechanism, can only be regarded as an imported product, PHP books on the abnormal mechanism of the discussion is very few, mostly only in the grammar stage. Some people praised the PHP exception is a good thing, also some people think that PHP exception is not to force, also some people have been confused in PHP should not use the exception, how to use?

The syntax of the exception itself is not worth discussing, the exception of the use of the scene is the main, here I compare PHP and Java, look at the exception in PHP what is going on, how the exception should be used.
See the PPC Forum on this discussion, feel very valuable, I re-organized the next point of view, to do a summary.
First of all, it is necessary to say that the exception here refers to the exception of PHP. Because PHP exceptions differ greatly from other languages.
The exception in PHP is that the program is running in a situation that is not expected to occur, that is, a process that is allowed to happen within the program execution flow, only in a different condition than the normal process. It is an abnormal situation, that is, according to our normal logic should not be wrong, but still the error, is a logical and business process error, not a grammatical error.
Errors in PHP are an illegal, grammatical, or environmental problem that causes the compiler to fail to check or even run.
PHP's exception handling is to do with your program when running a situation to handle, is not an error, the exception is the program run results are not what you want. For programs, exceptions are not controllable, and we cannot control which part of the runtime will go wrong, but we can anticipate what links will go wrong and make targeted remediation.
The concepts and distinctions of exceptions (exception) and errors (error) are not the same in various languages. In Java and PHP, the definition of errors and exceptions is also different. In PHP, it encounters any self-error that triggers an error instead of throwing an exception (in some cases, throwing exceptions and errors together). Once PHP encounters abnormal code, it usually triggers an error instead of throwing an exception. In this sense, if you want to use exceptions to handle unforeseen problems, you can't. For example, if you want to trigger an exception when the file does not exist and the database connection is not open, it is not feasible. This is a mistake in PHP, and PHP throws it as an error and cannot be automatically captured as an exception. Java, in contrast, sees many behaviors as exceptions and captures.
Let's take one of the most straightforward examples. Take the classic example of a 0 problem:

The code is as follows Copy Code
exception.php
$a =null;
try{
$a =5/0;
echo $a, php_eol;
}catch (Exception $e) {
$e->getmessage ();
$a =-1;
}
echo $a;

Operation Result:

Here is the Java code: Exceptiontry.java

The code is as follows Copy Code
Exceptiontry.java
public class Excepetiontry {
public static void Tp () throws arithmeticexception{
int A;
a=5/0;
SYSTEM.OUT.PRINTLN ("Result of the operation:" +a);
}

public static void Main (string[] args) {
int A;
try {
a=5/0;
SYSTEM.OUT.PRINTLN ("Result of the operation:" +a);
} catch (ArithmeticException e) {
E.printstacktrace ();
}finally{
A =-1;
SYSTEM.OUT.PRINTLN ("Result of the operation:" +a);
}
try {
EXCEPETIONTRY.TP ();
} catch (Exception e) {
SYSTEM.OUT.PRINTLN ("exception is captured");
}

}
}

Operation Result:

If we change the second clause in the TP method to the following:
A=5/1;
Then the result will be as follows:

From the above results can be seen, in addition to the "exception" code 0, PHP think this is a mistake, will directly trigger the error (Waring is also a mistake, but not the same level of error), and does not automatically throw an exception to enter the abnormal process, so the final value of $ A is not expected-1, that is, Does not enter the exception branch, nor does it handle the exception. PHP can catch exceptions only if you are actively thrown (this is the case, and some exceptions are automatically captured by PHP).
The exception handling mechanism is used in the following three scenarios:
(1) Pessimistic forecast of the procedure
If a programmer has a "pessimistic sentiment" about his code, this does not mean that the programmer's code is not high quality. He doesn't think his code can handle all the foreseeable unforeseen situations, and the programmer will handle the exception. Assuming a scenario where the programmer is pessimistic about the possibility of a deadlock in a high concurrency condition, then he will throw the exception in a pessimistic manner and then capture it during a deadlock and fine-grained the exception.
(2) The needs of the program and the attention to the business
If programmers want the business code to be not flooded with large stacks of printing, debugging, and so on, usually they will use the exception mechanism, or business needs to define some of their own exceptions, this time you need to customize an exception to the real world of a variety of business to complement. For example, to be late for work, this situation, I think is an anomaly, to collect, to concentrate on the end of the month, deduct your salary; If the programmer wants to anticipate the potentially occurring code that will affect the normal business, it needs an exception. Here, it is emphasized that the anomaly is an essential part of the business process and cannot be ignored by the exception. The anomaly mechanism argues that data consistency is important, and that an anomaly mechanism is needed to remediate the data when it can be compromised.
For example, for example, there is a business need to upload files, to save the uploaded files in a directory, and in the database to insert the record of this file, then these two steps are interrelated inseparable of an integrated business, indispensable. File save failed, and inserting a record successfully results in the inability to download the file, while the file save successful database write fails, it will cause the files that are not logged to become dead files and will never be downloaded.
Then we assume that the file is saved successfully without prompting, but the save failure will automatically throw an exception, access to the database is the same, the insertion succeeds without prompting, the failure automatically throws an exception, we can put the two potentially thrown exception code snippet in a try statement, and then catch the error in the catch, Delete files that are not logged to the database or delete records without files in the catch code snippet to ensure consistency of business data. Therefore, from the perspective of business, the exception is biased to protect business data consistency, and emphasizes the handling of abnormal business.
If our code is just symbolic of the try-catch, finally print an error, over. Such an anomaly, rather than use, did not reflect the idea of abnormal. Therefore, the reasonable code should be as follows:

The code is as follows Copy Code
try{
Code snippet with possible error
if (file upload is unsuccessful) throw (upload exception);
If (insert database is unsuccessful) throw (database operation exception);} catch (Exception) {
Necessary remedial measures, such as deleting files, deleting database insert records, this processing is very meticulous
}
//....
?>

can also be as follows:

The code is as follows Copy Code
Upload
if (file upload is unsuccessful) throw (upload exception);
If (insert database is unsuccessful) throw (database operation exception);
}
Other code ... try{
Upload
Other
}catch (Upload exception) {
Necessary remedial measures, such as deleting files, deleting database insert records
}catch (other exceptions) {
Log log
}
?>

The above two methods of catching exceptions, the first one is caught immediately when an exception occurs, and the latter is a scatter throw anomaly, which is captured centrally. Which one should it be?
If our business is important, the sooner the exception is processed, the better, to ensure that the program can maintain the consistency of business processing in unexpected situations. For example, an operation has more than one prerequisite step, suddenly the last step is abnormal, then the other prerequisite operations to eliminate the line, to ensure data consistency. And in this core business, there is a lot of code to do the aftercare, data recovery, this is a more pessimistic exception.
If our anomalies are not so important, and in a single-entry, MVC-style application, in order to maintain the unity of the Code flow, the latter exception handling is often used, the exception handling more emphasis on the business process, the aftermath of the work is not very concerned about. This is an optimistic exception.
(3) Requirements for the robustness of the language level
At this point, PHP is missing. In Java, for example, Java is a language for enterprise-level development, emphasizing robustness. Multi-Threading is supported in Java, and Java believes that multithreading is interrupted this situation is completely unpredictable and avoidable. So Java rules that if you use multiple threads, you have to face this situation. You either throw it, whatever it is, or catch it and handle it. In short, you have to face interruptedexception this anomaly, don't avoid. That is, after the exception happens to the important data business to remedy, of course you can not do, but I will tell you, this is what you should do. This type of exception is mandatory. More exceptions are non-mandatory and are determined by the programmer. Java's classification and restriction of exceptions ensure the robustness and trustworthiness of Java programs.
So what's the point of the anomaly?
An exception is a run-time error that cannot be controlled, causing the normal logic to run when an error occurs, and the logic behind the exception code cannot continue to run. The benefit of the try/catch is that it can minimize the disruption of the logical interrupt caused by the exception, and that after remedial action it does not affect the integrity of the business logic, throwing out anomalies and only throwing and not capturing, or capturing without remediation, can result in data confusion. This is an important function of exception handling, that is, when we precisely control the run-time process, when the program is interrupted, there is a predictable use of try to narrow the scope of possible errors, and then timely catch the occurrence of the exception and make a corresponding remedy, so that the logic process can still return to normal orbit.
How to see PHP exceptions?
We have seen the exception mechanism in PHP is very chicken, most of the cases can not automatically throw the exception, you must use If-else to judge first, and then manually throw the exception. This approach looks more like a superfluous. The meaning of the manual throw exception is not very big, because you manually throw the exception also means that you have fully anticipated the error in the code, and even if not really "abnormal", but not expected. Still fall into the complex business logic judgment and processing. Java and the C + + language to do a better thing is to define a bunch of built-in common exceptions, do not need the programmer to judge the various anomalies after the hand-thrown, the compiler will judge for us whether the business error, automatically throw an exception. As a programmer, you only need to be concerned about the exception capture and subsequent remediation, rather than what happens in PHP like in the end of the exception ah, with If-else to judge each, throw the exception.
PHP abnormal mechanism is not perfect, in many cases and if-else compared with no obvious advantage, this is the exception of PHP is not popular reason. Of course, the use of anomalies can also reduce the coupling to a certain extent.
So how to improve the original PHP exception handling mechanism? At this point, it is necessary to use PHP error handling. PHP provides a Set_error_handler function that allows you to customize the error handling function to turn non-fatal types of error handling into your own defined functions for analysis and processing. But because there may be a lot of mistakes, it is very complicated to distinguish between them, so we only use this feature as a springboard. In the custom function, we manually throw an exception, kill a greatest second act, let Try/catch can capture and handle the interruption caused by this runtime error, so as to achieve the purpose of expanding the scope of Try/catch influence.

http://www.bkjia.com/PHPjc/631606.html www.bkjia.com true http://www.bkjia.com/PHPjc/631606.html techarticle PHP anomaly mechanism, can only be regarded as an imported product, PHP books on the abnormal mechanism of the discussion is very few, mostly only in the grammar stage. Some people praised the PHP exception is a good thing, also someone ...

  • 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.