I've seen a few questions about lambdas and exceptions, but I still don't understand the behavior I'm seeing in my code.
class MyObj
{
public object Prop1 { get; set; }
}
public void Get()
{
try
{
IEnumerable<MyObj> collection = new List<MyObj>() { new MyObj() };
collection = collection.Where(x =>
{
return x.Prop1.ToString() == "some value";
});
}
catch (Exception ex)
{
throw new UriFormatException($"Invalid filter. Error details: {ex.Message}");
}
}
Since Prop1
is null, an "Object reference not set to an instance of an object" exception is thrown. However, the code doesn't enter the catch
block. If I add some more code that attempts to use collection
in the try
block, the catch
block is entered when the exception is encountered in the lambda. E.g.
foreach (var c in collection)
{
Console.WriteLine(c);
}
I'd like the catch block to be entered if there's any exception when executing the lambda. I've tried writing a named function to call from the lambda, that doesn't work either. What am I missing?