Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Decimal.Round() throw OverflowException

I'm using

Decimal.Round(decimal d)

MSDN says it can throw OverflowException https://msdn.microsoft.com/en-us/library/k4e2bye2(v=vs.110).aspx

I'm not sure how that can happen. I tried looking over the implementation using ilSpy And got until the external implementation of:

// decimal
[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void FCallRound(ref decimal d, int decimals);

Does anybody got a clue what input can throw this exception?

like image 397
Amir Katz Avatar asked Feb 20 '17 15:02

Amir Katz


1 Answers

When we go further from what you already discovered yourself, we end up in the implementation of the VarDecRound function. This function has exactly one branch where it returns an error code, and that is when its second argument cDecimals is smaller than zero. This argument indicates the number of decimal digits to round to:

if (cDecimals < 0) 
    return E_INVALIDARG; 

(this kind of assertion is the equivalent of what an ArgumentException would be in .NET)

As James Thorpe pointed out in a comment on OP, a similar assertion is done further up the call chain, here:

if (decimals < 0 || decimals > 28) 
    FCThrowArgumentOutOfRangeVoid(...)

Conclusion:
Execution cannot reach the point that would result in throwing the OverflowException as documented:

  1. OverflowException seems to have been used internally as a catch-all mechanism, much like OutOfMemoryException in GDI+
  2. The documentation does not match the actual implementation
  3. OverflowException does not even make sense conceptually. Rounding a value up or down in the same data type cannot possibly exceed an integral min or max range, because the candidate value must itself be in range (rounding method used)
like image 178
Cee McSharpface Avatar answered Nov 14 '22 16:11

Cee McSharpface