简体   繁体   English

什么时候遍历列表会引发Null Reference Exception?

[英]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? 我应该在遍历列表的任何地方都捕获Null引用异常吗?

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? 我怎么知道什么时候应该捕获一个Null引用异常来遍历一个列表以及什么时候不必要?

There will be no NullReferenceException if your list is empty. 如果您的列表为空,将没有NullReferenceException 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. 如果您的容器本身有可能为nullif在循环之前应使用简单的if进行检查。 It might be a good practice to not let it become null in the first place though. 最好不要让它最初为null 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 . 在这种情况下,早期的失败并引发ArgumentNullException如果你得到你希望是不是一个集装箱null ,而不是试图达成协议的事实,它 null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这会引发空引用异常? - Why does this throw a null reference exception? 使用List(Of Entity)绑定到DataGridView Datasource属性会引发空引用异常 - Binding to DataGridView Datasource property with List(Of Entity) throw a null reference exception 为什么会话对象抛出空引用异常? - Why does session object throw a null reference exception? 为什么这个嵌套对象初始化器抛出一个空引用异常? - Why does this nested object initializer throw a null reference exception? 为什么枚举通过集合抛出异常但循环遍历其项目却没有 - Why does enumerating through a collection throw an exception but looping through its items does not 为什么MVC在似乎没有Null引用时会抛出NullReferenceException? - Why does MVC throw a NullReferenceException when there seems to be no Null Reference? 清单,ObservableCollection的清单 <Image> 循环时出现null - A list of, list of ObservableCollection<Image> comes up null when looping through it 是否应引用null变量引发异常 - Should a reference to a null variable throw exception 循环遍历DirectoryEntries时出现异常 - Exception when looping through DirectoryEntries 为什么 HttpRequestMessage.Content.Headers.ContentType 会抛出 null 引用异常? - Why does HttpRequestMessage.Content.Headers.ContentType throw null reference exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM