We have have a block of code that generates a lot of exceptions (IndexOutOfRangeException apparently). It’s possible that it generates up to 50,000/sec. They are caught but the cpu really spikes. The code block simply checks an IDataRecord for a column. The block is very generic though and if the column isn’t there, the exception is caught and returns a boolean.
If it weren’t for the number of exceptions this wouldn’t be an issue. The only way I can think to fix this is to iterate through the columns of the IDataRecord to see if the column is there before processing, but this also seems like it could be an expensive step because this is a very high traffic application and you would have this loop before accessing any column.
I’m just looking for some thoughts.
Make sure the columns you’re looking for exist first. Not only is throwing exceptions usually an even bigger hit performance-wise, but all those spurious exceptions might be hiding legitimate bugs in the code.
The best way to make sure the columns exist first is to bring all those
IDataRecordclasses in line with this function’s assumptions about what kind of data they contain. Or bring the function in line with the actual data. Having a procedure assume that a value exists when it doesn’t implies that your program’s structure is not a good match for the business logic it implements, and that’s a situation that shouldn’t be allowed to persist.Second up would be to loop through each object’s fields to see what it actually contains that field, but this smells of sweeping a deeper problem under the carpet.
On no account, though, should you be relying on exceptions for control flow.