When should we use exceptions?

Source: Internet
Author: User
Tags error status code
& Amp; bull; author: Laruence (): I think it makes sense to do two things at the company. The first is to set up a PHP contact group, the second is to set up an Hi group. at present, both of them have more than 500phpers in it. I always think that building a transaction... syntaxHighlighte • By Laruence ()

Let me talk about the problem first: I think it makes sense to do two things in the company. The first is to set up a PHP contact group and the second is to set up a Hi group. at present, both of them have more than 500 phpers in it. I have always believed that building a communication platform that enables smooth and simple communication is the basis and prerequisite for creating a positive technological learning atmosphere. it is the most direct benefit to prevent everyone's problems from being problems of others.
Yesterday, a colleague raised a question in the contact group:
When should PHP use Exception? What is its performance?
This is also a classic question that has been controversial for a long time. let me talk about my personal opinion.
What are the advantages and disadvantages of the corresponding error codes (or status codes) of exceptions? How should we use them?
Error code
First, the exception mechanism occurs only after the error code mechanism. according to the evolution, exceptions naturally avoid some shortcomings of the error code mechanism. These shortcomings include.
1. the error information is not rich
A function can only return one value (of course, Lua can return multiple values, but it is also equivalent to returning an array in PHP). The most common function descriptions we have seen are: * ** is returned when a function is successful, and FALSE is returned when an error occurs. However, there may be many reasons for a function error, and there are more types of errors. A simple FALSE statement does not tell the caller specific error information.
As a result, we have seen some such functions: if the return value is greater than 0, it indicates the success status code. if the return value is smaller than 0, it indicates the error status code.
However, this requirement is that the function returns an integer (or number). For some other functions, we cannot identify them by 0,> 0, or <0, and even in this way, we also need to use the returned error code and some predefined macros (or call strerror () to obtain specific and readable error information.
Therefore, some functions use global error codes and error messages to save specific error information. at this time, we can see the function description: Success returns ***, if an error occurs, FALSE is returned. the error code is stored in the global variable $ errno (at least most Linux library functions are described in this way ).
Okey, this method does work, but do you think it is ugly?
2. adding an error code may require changing the function signature.
Assume that you have compiled a function. This function is very simple. you think it will never go wrong, so you declare it as (using C language as an example, PHP does not return a type prompt ):
1. void dummy (){
2 .}
But then you slowly modified this function and gave it more functions. at this time, this function may fail, and you cannot add an error return code for this function.
Some people may say that PHP has no limit on the type of returned values, but think about PHP constructor. constructor does not return values. If an error occurs, if you do not use an exception, I think you can only select die, or use the method in step 2 to continue the execution.
In addition, in a good software system, the return type is also customary. when no function is used to check the return value, you still cannot add an error return code for this function.
3. the error status code may be ignored.
When an error occurs in a function and an error status code is returned, the caller does not check the returned value. what will happen? -_ #. On the one hand, the returned status code is detected everywhere, which may cause very bad codes. Uugly:
1. 2. if (! Call1 ()){
3. die ();
4 .}
5.
6. if (call2 ()! = SUCCESS ){
7. die ();
8 .}
9.
10. if (call3 () <0 ){
11. $ msg = error_get_last ();
12. die ($ msg ["message"]);
13 .}
Exception mechanism
Now let's look at the exception mechanism. if we adopt the exception mechanism, the above code can be written:
1. 2. try {
3. call1 ();
4. call2 ();
5. call3 ();
6.} catch (Exception $ e ){
7. die ($ e-> getMessage ());
8 .}
It is more convenient. if your code is only an intermediate layer, your caller will be responsible for handling errors, and you can even simply write:
1. 2. function myFunc (){
3. call1 ();
4. call2 ();
5. call3 ();
6 .}
An exception object can contain more extensive error information, such as error information, error codes, number of wrong lines, files, and even error context. insufficient error information.
We can also add an exception for a function that returns the void type without changing its function signature, so there will be no "2. adding an error code may require changing the function signature ". for PHP, if the newly added errors are not captured, you don't have to worry about them. the errors will be obvious. the above-mentioned "3. the error status code may be ignored.
However, there are also some voices against usage exceptions:
1. performance
As in the question at the beginning of the article, "How is its performance ?", The exception mechanism is indeed more expensive than the return status code method. for C ++, stack rollback occurs when an exception occurs (for PHP, there is no such logic, for details, refer to the article I wrote: an in-depth understanding of the exception mechanism of PHP principles ).
Performance and convenience are often a contradiction. I can only say that you need to weigh. if you write a small module and its life cycle may be very short, you do not need any special design patterns.
If you are developing a huge software, I think you should pay more attention to it. it is scalable and maintainability.
2. too many possible Uncaught exceptions
If you call a function that may have an exception, but it does not catch the exception, okey and Fatal Error, let our code look like:
1. 2. try {
3.} catch (){
4 .}
5 .....
6.
7. try {
8.} catch (){
9 .}
10 .....
11. try {
12.} catch (){
13 .}
However, this can be avoided through good design. for example, when I design Yaf, it provides global exception handling, which is similar to that you are at the top layer, with a try catch, all the exception and error logics are added to this file. you can also easily add your own exceptions.
Conclusion
Some people often criticize me for being a face-to-face school. but after everyone understands the advantages and disadvantages, will they share the same idea with me: is this a final matter? Everything starts from reality.
If you have said so much about it, I would like to discuss it with you.
 
 

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.