简体   繁体   中英

When does looping through a list throw a Null Reference Exception?

I haven't really done much exception handling before (fairly new to coding) and I'm unsure about where I need to catch exceptions and where there should be no exceptions to catch.

Specifically, I'm wondering about iterating through lists. Should I catch a Null Reference Exception everywhere that I loop through a list?

I'm thinking the answer is No since I have unit tests which test code that loops through a list and they do not throw an exception when the list has no elements.

So, I'm wondering. How do I know when I should catch a Null Reference Exception for looping through a list and when it is unnecessary?

There will be no NullReferenceException if your list is empty. You can iterate over empty containers just fine.

If there is a chance that your container itself is null you should check this with a simple if before you loop. It might be a good practice to not let it become null in the first place though. Fail early in that case and throw an ArgumentNullException if you get a container that you expect to be not null instead of trying to come to terms with the fact that it is null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM