157 recommendations for writing high-quality code to improve C # programs--Recommendation 62: Avoid nesting exceptions

Source: Internet
Author: User

Recommendation 62: Avoid nesting exceptions

Exceptions should be allowed to upload on the call stack, do not use catch too much, and then throw. Excessive use of catch brings two problems:

1) More code. It looks as if you don't know how to deal with exceptions, so you always catch them all the time.

2) hides the stack information so that you don't know where the exception really happened.

Nesting without reason is what we should try to avoid. Of course. If you really need to catch this exception to restore some state and then re-throw it, the code should look like this:

            Try             {                //...             }            catch  (Exception)            {                // work code                Throw ;            }

Or:

            Try             {                //...             }            catch            {                // Work code                Throw ;            }

Try to avoid throwing exceptions like this:

            Catch (Exception ex)            {                //                Throw ex;            }

A direct throw ex instead of a throw resets the stack information.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 62: Avoid nesting exceptions

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.