Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exception

linq

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?

like image 716
Konrad Viltersten Avatar asked Mar 09 '26 05:03

Konrad Viltersten


2 Answers

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();
like image 146
nicolas2008 Avatar answered Mar 11 '26 19:03

nicolas2008


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();
like image 29
Henk Holterman Avatar answered Mar 11 '26 19:03

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!