For and foreach/throw and throw ex usage notes

Source: Internet
Author: User

Foreach is very convenient for loop sets, but it is not suitable for all times

1. For is available at any time. There is no doubt that only one point of attention is that an inverted loop is used to delete items in a set or array. The reason is:

1) The positive loop jumps and the index goes through the border. For example, there are five records in the set. When you delete the third record (the index is 2), the actual length of the array is changed to 4 after the array is adjusted, the number of cycles increases to 3, but the index of the original 3 in the array is changed to 2. In this way, you access the record with the index of 4, when you access index 4, the index is thrown out when the length of the array changes.

2) use an inverted loop to traverse from the largest index to solve the above problem.

2. foreach is only suitable for the set that implements the default iteration, and can only perform the unchanged operation. It is not suitable for the Add/delete operation of the set. In this case, you must use for. Others are basically the same as

Throw and throw ex

1. Throw is an abnormal bubble mechanism. The source of the exception remains unchanged, and the error message remains unchanged.

2. Throw ex throws an exception again. The exception source is changed to the current class, and the exception prompt information remains unchanged.

In general, we should make the exception bubble or handle it, instead of re-throwing the exception, unless you do not need a system exception, but here we need to change the prompt information to a custom exception.

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.