Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operation resulted in an overflow. (Adding integers)

I can't understand this error:

In this call to method SetVolume, Volume = 2055786000 and size = 93552000. Volume is an Integer property, and size is also Integer, as you can see.

The class is a partial class of a dbml entity class, however this Volume property is NOT a column in the database, it exist only in the partial class, as a "business object property".

View Detail shows:

Data > Item : In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.

alt text

What may cause this...?

like image 264
bretddog Avatar asked Jan 21 '11 07:01

bretddog


People also ask

How do you handle arithmetic overflow?

If you want to ensure that arithmetic operations will throw overflow exceptions if an overflow happens, you need to use the checked { ... } code block. When using the checked { ... } code block, if any arithmetic operation causes an overflow, an OverflowException will be thrown, and will need to be catched and handled.

What is overflowing in c#?

January 22, 2014 in .net, c# Arithmetic overflow happens when you perform an operation with a data type and the result of this operation exceeds the size of a storage for this datatype. For example, when you add two large 32-bit integers together and the result cannot fit into Int32 and overflows.

How do you handle arithmetic overflow exception in C#?

For the arithmetic, casting, or conversion operation to throw an OverflowException, the operation must occur in a checked context. By default, arithmetic operations and overflows in Visual Basic are checked; in C# and F#, they are not.


1 Answers

The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

like image 172
Botz3000 Avatar answered Sep 23 '22 05:09

Botz3000