157 suggestions for writing high-quality code to improve C # programs [avoid Invalid code in finaly, avoid nested exceptions, avoid eating exceptions, and handle loop exceptions]

Source: Internet
Author: User

Preface

This article has been synchronized to http://www.cnblogs.com/aehyok/p/3624579.html. This article focuses on the following suggestions:

61. Avoid writing Invalid code in finally.

Suggestion 62. Avoid nested exceptions

Recommendation 63. Avoid "eat" exceptions

We recommend that you add the Tester-Doer mode for the loop instead of placing try-catch in the loop.

61. Avoid writing Invalid code in finally.

Let's take a look at three simple try catch methods.

Public class User {public string Name {get; set ;}} class Program {static void Main (string [] args) {Console. writeLine (Test1 (); Console. writeLine (Test2 (); Console. writeLine (Test3 (). name); Console. readLine ();} public static int Test1 () {int I = 0; try {I = 1;} finally {I = 2; Console. writeLine ("\ t changes the int result to 2, and finnally execution is complete. ");} Return I;} public static int Test2 () {int I = 0; try {return I = 1;} finally {I = 2; Console. writeLine ("\ t changes the int result to 2, and finnally execution is complete. ");}}

You probably have an answer after reading the code.

It is easier to explain these issues through IL, so we will not repeat them here.

In CLR, the parameters and returned values of methods are stored in stacks. Inside the method, the parameters are pushed to the stack in sequence. When these parameters are required, the method directly uses the parameter values in the stack. When the method returns, the return value is pushed to the top of the stack. If the parameter type is a value type, the stack is the copied value. If the parameter type is a reference type, modifications to the parameter in the method will also be taken out of the method.

Suggestion 62. Avoid nested exceptions

As mentioned in recommendation 59, exceptions should be allowed to be propagated in the call stack. Do not use catch too much and throw the exception. Using catch will cause two problems:

1. More code. It seems that you don't know how to handle exceptions at all, so you keep catch.

2. The stack information is hidden so that you do not know where an exception actually occurred.

Let's take a look at the code below the idea.

        static void Main(string[] args)        {            try            {                Console.WriteLine("NoTry\n");                MethodNoTry();            }            catch (Exception exception)            {                Console.WriteLine(exception.StackTrace);            }            try            {                Console.WriteLine("WithTry\n");                MethodWithTry();            }            catch (Exception exception)            {                Console.WriteLine(exception.StackTrace);            }            Console.ReadLine();        }        public static int Method()        {            int i = 0;            return 10 / i;        }        public static void MethodNoTry()        {            Method();        }        public static void MethodWithTry()        {            try            {                Method();            }            catch (Exception exception)            {                throw exception;            }        }

Execution result

It can be found that the MethodNoTry method can be used to view where an exception occurs, while MethodWithTry does not know where the error occurs. The call stack times reset. If there are other exceptions in this method, the UI Layer will never know where the error actually occurred, causing a lot of trouble for developers.

In addition to packaging exceptions mentioned in recommendation 59, nesting exceptions for no reason should be avoided. Of course, if you really need to capture this exception to restore some state and then throw it again, the code should be like this:

Try {MethodWithTry ();} catch (Exception) {// work code throw ;}

Or make some changes.

Try {MethodWithTry ();} catch {// work code throw ;}

Avoid exceptions as follows:

Try {MethodWithTry ();} catch (Exception exception) {// work code throw exception ;}

Directly throw exception instead of throw will reset the stack message.

 

Recommendation 63. Avoid "eat" exceptions

After reading the suggestion 62, you may already understand that nested exceptions are very dangerous and will hide the exception stack information, that is, the real Bug source. But this is not the most serious behavior. The most serious is the "eat" exception, that is, capture and then throw the throw to the upper layer.

To avoid the "eat" exception, it does not mean that the "eat" exception should not be avoided, but there is an important principle: this exception is sadly foreseen, and it is generally not a Bug.

Imagine that you are decrypting tens of thousands of files. These files come from different clients and may be damaged by file times. Your goal is to insert the decrypted data into the database. At this time, you have to ignore the decryption failures and let the process proceed. Of course, it is necessary to record logs, because in the future, you may perform unified processing on files that fail to be decrypted.

In another case, you may not need to record logs. In a distributed system that controls thousands of controlled terminals, the control end needs to send heartbeat data to determine the online status of the controlled end. The common practice is to maintain a semaphore. If the sending of Heartbeat Data fails at an acceptable blocking time such as 500 ms, the control thread will not receive the signal, you can determine the disconnection status of the controlled end. In this case, it is usually meaningless to record each SocketException.

All the elements of this suggestion are: if you do not know how to handle an exception, do not "eat" the exception. If you "eat" an exception that should have been passed on the internet, A BUg may be generated here, and it will be very costly to solve it.

We recommend that you add the Tester-Doer mode for the loop instead of placing try-catch in the loop.

If an exception needs to be thrown in a loop, you need to pay special attention because throwing an exception is a process that affects performance. We should try to judge the conditions for exceptions in the loop and then process them according to the conditions. You can perform a test:

        static void Main(string[] args)        {            CodeTimer.Initialize();            CodeTimer.Time("try..catch..", 1, P1);            CodeTimer.Time("Tester-Doer", 1, P2);            Console.ReadLine();        }        public static void P1()        {            int x = 0;            for (int i = 0; i < 1000; i++)            {                try                {                    int j = i / x;                }                catch                {                                     }            }        }

The gap is quite obvious. In the above Code, we anticipate that a DivideByZeroException exception may occur in the Code. Therefore, we adjusted the policy and performed special processing on the exception conditions: Continue, which greatly improved the efficiency.

 

Tips for English

1. How much? -- How much?
2. I'm full. -- I'm full.
3. I'm home. -- I'm back.
4. I'm lost. -- I'm lost.
5. My treat. -- treat me.
6. So do I. -- the same is true for me.
7. This way. -- here, please.
8. After you. -- you first.
9. Bless you! -- Bless you!
10. Follow me. -- come with me.

Author: aehyok

Source: http://www.cnblogs.com/aehyok/

Thank you for reading this article. If you are interested in the content described in my blog, please make a suggestion. Thank you for your support:-O.

 

Related Article

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.