LINQ Interview Question #93

How does deferred execution affect exception timing?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

Because a deferred query is not fully executed when it is defined, some exceptions caused by enumeration occur later, when the query is consumed.

Detailed Explanation

Because a deferred query is not fully executed when it is defined, some exceptions caused by enumeration occur later, when the query is consumed.

This can surprise developers who place only the query definition inside a try block. Understanding the execution point helps place validation and exception handling correctly.

Code Example

IEnumerable<int> query =
    values.Select(v => 100 / v);

// DivideByZeroException may occur here:
foreach (var value in query)
{
    Console.WriteLine(value);
}