Why doesn't the catch statement catch all the

2020-07-23 08:12发布

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?

3条回答
聊天终结者
2楼-- · 2020-07-23 08:39

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();
查看更多
霸刀☆藐视天下
3楼-- · 2020-07-23 08:42

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();
查看更多
老娘就宠你
4楼-- · 2020-07-23 08:46

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

查看更多
登录 后发表回答