Why doesn't the catch statement catch all the exceptions? [duplicate]

十年热恋 提交于 2020-01-01 18:57:11

问题


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



来源:https://stackoverflow.com/questions/36828822/why-doesnt-the-catch-statement-catch-all-the-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!