相关疑难解决方法(0)

为什么catch语句没有捕获所有异常?

我正在测试下面的方法,我意识到当我输入错误的文件名时,错误会被捕获,但是当我在指定的位置上没有元素时,IndexOutOfBounds的错误会使程序崩溃.后者也用于转换错误.

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>();
  }
}
Run Code Online (Sandbox Code Playgroud)

尽管catch中最常见的Exception类型,为什么不处理某些错误?是否与LINQ表达式失败有关?如果是这样,我该如何强行捕捉呢?

c# linq exception

2
推荐指数
2
解决办法
126
查看次数

标签 统计

c# ×1

exception ×1

linq ×1