Why doesn't the catch statement catch all the

2020-07-23 08:06发布

问题:

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?

回答1:

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();


回答2:

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();


回答3:

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