How do I gracefully test overflow situations in C #?

Update: I'm going to leave it as it is: Declining exception performance (very rare) is better than probably performance for checking each operation (overall)


I am trying to support "EstimatedRowCount", which in one case will be the product of two sub-cursors that are connected together:

estimatedRowCount = left.EstimatedRowCount * right.EstimatedRowCount; return estimatedRowCount; 

Of course, if the left and right are large enough, this will throw an OverflowException.

Here, I donโ€™t care if the estimated RowCount is 100% accurate, large enough to know that this cursor contains a lot of data.

Now I am doing this:

 // We multiply our rowcount Int64 estimRowCount = 0; try { estimRowCount = leftRowCount * rightRowCount; } catch (OverflowException) { // Ignore overflow exceptions estimRowCount = Int64.MaxValue; } return estimRowCount; 

Is there a better way to check overflow operations, so I donโ€™t need to do try {} catch for protection?

+4
source share
3 answers

That sounds like a good use case for the 'unchecked' keyword .

To use, just leave your destination in the "unchecked" block:

 Int64 estimRowCount = 0; unchecked { estimRowCount = leftRowCount * rightRowCount; } 

Then check if the result is negative - if it is, it is full:

 if (estimRowCount > 0) estimRowCount = Int64.MaxValue; 

In this case, you need to make sure that neither leftRowCount nor rightRowCount can be negative, but in the context, I do not think this will happen.

+4
source
 if (Int64.MaxValue / leftRowCount <= rightRowCount) { estimRowCount = leftRowCount * rightRowCount } else { estimRowCount = Int64.MaxValue; } 

Not sure if I could explain myself without an editor. But, I hope you get the idea.

+4
source

Your decision seems quite reasonable. Is there anything specific you want to optimize? Does this product cause an excessive state so often that you are worried about a hit in exception handling performance?

(Just simple food for thought, if leftRowCount and rightRowCount are Int32, not Int64, then your product cannot overwhelm your Int64 valuRowCount lvalue score.)

+3
source

All Articles