问题描述
我正在测试下面的方法,我意识到当我输入错误的文件名时,会捕获错误,但是当我在指定位置没有元素时,会出现 IndexOutOfBounds 错误使程序崩溃.后者也可用于转换错误.
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>();
}
}
为什么尽管 catch 中使用了最普通的 Exception 类型,仍然没有处理一些错误?它与LINQ表达式失败有关吗?如果是这样,那么我该如何强制捕获?
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?
推荐答案
这是因为您返回IEnumerable.Select中的lambda不会立即执行,而只会在访问可枚举(迭代项)时执行.
This is because you return IEnumerable.The lambda inside Select doesn't execute immediately, but only on accessing the enumerable (iterating items).
如果在选择"之后添加调用"ToArray",则将计算所有项目,并且将在catch块中捕获IndexOutRangeException.
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();
这篇关于为什么catch语句不能捕获所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!