Lets say I have this code:
IDictionary<int, int> itemPriceDict = loadItemPriceDictionary();
IList<IRow> dbItems = loadItemsFromDatabase();
IList<ItemDTO> itemDTOs = dbItems
.Select(dbItem => new ItemDTO()
{
Id = dbItem.Id,
Label = dbItem.Label,
PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
})
.ToList();
and I sometimes get an KeyNotFound exception when given price tag does not exist for the given dbItem.
Now, when debugging in Visual Studio and an exception is thrown, you can see StackTrace, TargetSite which show you what line of code triggered it, but is it possible to find out what object (dbItem) caused the exception and display it's data in Debugger? For example in Watch window?
I would like to:
But without any need to add or modify any code.
P.S.: I know I can rewrite the code as cycle, but I would like not to.
You could write your Select as such :
.Select(dbItem =>
{
return new ItemDTO()
{
Id = dbItem.Id,
Label = dbItem.Label,
PriceTag = itemPriceDict[dbItem.Id] // Possible KeyNotFoundException
})
}
.ToList();
That would allow you to place breakpoints inside the select evaluations.
Better yet, go in the Debug Menu, then select Exceptions (it is under the Windows submenu on my Visual Studio Edition).
Then set it up so that it breaks on either KeyNotFoundException or any exception of your choice.
The debugger will then automatically break when an exception occurs allowing you to inspect the state of the related objects
[disclaimer: I work at OzCode]
Have you tried OzCode. Linq debugging support was added to the EAP and one of the features is that it can predict if a query will throw an exception and show the offending item.

This way you don't need to dissect your code or try and debug it in your head.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With