Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception from LINQ query not caught where expected

Tags:

c#

exception

linq

I am parsing an input string to a class using a LINQ query. I have wrapped the query in a try/catch block to deal with parse errors. The problem is that the exception is not caught at the point at which I expect it to occur, it only stops program flow at the point at which the resulting object (parsedList) is accessed. Have I misunderstood something about how LINQ works or how exceptions work?

public class Foo
{
    public decimal Price { get; set; }
    public decimal VAT { get; set; }
}

public class MyClient
{
    public IEnumerable<Foo> ParseStringToList(string inputString)
    {
        IEnumerable<Foo> parsedList = null;
        try
        {
            string[] lines = inputString.Split(new string[] { "\n" }, StringSplitOptions.None);

            // Exception should be generated here
            parsedList =
                from line in lines
                let fields = line.Split('\t')
                where fields.Length > 1
                select new Foo()
                {
                    Price = Decimal.Parse(fields[0], CultureInfo.InvariantCulture),   //0.00
                    VAT = Decimal.Parse(fields[1], CultureInfo.InvariantCulture)    //NotADecimal (EXCEPTION EXPECTED)
                };
        }
        catch (FormatException)
        {
            Console.WriteLine("It's what we expected!");
        }

        Console.WriteLine("Huh, no error.");
        return parsedList;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClient client = new MyClient();
        string inputString = "0.00\tNotADecimal\n";
        IEnumerable<Foo> parsedList = client.ParseStringToList(inputString);
        try
        {
            //Exception only generated here
            Console.WriteLine(parsedList.First<Foo>().Price.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("Why would it throw the exception here and not where it fails to parse?");
        }
    }
}
like image 374
rudivonstaden Avatar asked Oct 22 '25 03:10

rudivonstaden


1 Answers

Unless you force execution, the LINQ query is not executed until it is actually needed ("deferred execution"). It may not even be executed completely - only those parts that are needed ("lazy evaluation").

See this : https://msdn.microsoft.com/en-gb/library/mt693152.aspx and this :https://blogs.msdn.microsoft.com/ericwhite/2006/10/04/lazy-evaluation-and-in-contrast-eager-evaluation/

You can force the complete execution immediately by adding something like .ToList() or .ToArray() to the end of the Linq query.

like image 183
PaulF Avatar answered Oct 24 '25 17:10

PaulF