This question already has answers here:
Closed 4 years ago.
I'm testing the method below and I realized that when I enter wrong file name, the error gets caught but when I don't have an element on the position specified, the error of IndexOutOfBounds crashes the program. The latter goes also for converting errors.
private static IEnumerable<Thing> Initialize()
{
try
{
string[] things = System.IO.File.ReadAllLines("things.txt");
return things.Select(_ => new Thing
{
Name = _.Split(';')[0],
Id = Convert.ToInt32(_.Split(';')[0])
});
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
return new List<Thing>();
}
}
Why doesn't some errors get handled despite the most general Exception type in the catch? Does it have to do with LINQ expression failing? If so, how do I force the catching, then?
This is because you return IEnumerable.
The lambda inside Select doesn't execute immediately, but only on accessing the enumerable (iterating items).
If you add call "ToArray" after "Select" then all items will be calculated and IndexOutRangeException will be catched in your catch block.
return things.Select(_ => new Thing
{
Name = _.Split(';')[0],
Id = Convert.ToInt32(_.Split(';')[0])
}).ToArray();
You are returning an IEnumerable<>
which implies deferred execution.
So anything inside the lambda is actually executing later, outside the try/catch.
If you want to catch all errors, include a .ToList()
, like
return things.Select(...).ToList();
I have experienced this a couple of years ago, and the explanation I found online is that it is because of unmanaged assemblies and code. Something that is out of the application domain. Mostly when you have a lower level (os level) operation