[英]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. 如果您的容器本身有可能为
null
, if
在循环之前应使用简单的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.