foreach (string s in myField.getChilds()) {
if (s == null)
//handle null
else
//handle normal value
}
When I run my program i get a NullReferenceException because getChilds may return null. How can I make my program to continue anyway and handle the exception? I can't handle it outside of the foreach, can't explain why because it will take too much time (and I am sure you guys are busy :P). Any ideas?
I already tryed that way:
foreach (string s in myField.getChilds() ?? new ArrayList(1)) {
if (s == null)
//handle null
else
//handle normal value
}
But it does not work, program just jump at the end of the foreach but I want it to enter the foreach instead!
Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.
Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place. You should never catch NullReferenceException.
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.
One way to do this (though not the best way) is:
foreach (string s in myField.getChilds() ?? new string[] { null })
or
foreach (string s in myField.getChilds() ?? new ArrayList { null })
The reason new ArrayList(1)
doesn't work is that it creates a list that has the capacity to hold 1 element, but is still empty. However new string[] { null }
creates a string array with a single element which is just null, which is what you appear to want.
var children = myField.getChilds();
if (children == null)
{
// Handle the null case
}
else
{
foreach (string s in children)
{
}
}
or simply use the null coalescing operator:
foreach (string s in myField.getChilds() ?? Enumerable.Empty<string>())
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With