Wednesday, April 24, 2019 04:27

Overflow exception

You should already know by now that the type of a variable defines the interval of values that it can store and the operations that the software can execute upon them. An int type can store, for instance, values ranging from -2,147,483,648 to 2,147,483,647. If you try to assign a value outside of this interval to an int, you will find yourself in what programmers call overflow exception.

An int variable stores 32 bits. The compiler uses the most significant bit to determine the sign of the variable, 0 being positive and 1 negative. Therefor, the program uses 31 bits to represent the value of the variable. To understand why the overflow exception occurs, you must have a look at the binary representation of the variable’s value. Lets consider the following values:

You can test this by yourself, using the following program:

The result will be this:

overflow exception

Additional Information

You may have noticed we used the following line:

So, we are printing a line on the console output, using a string of which you will learn later as being a variable that can store text. Inside it you can notice the {0} and {1} items, and after it, the negative and negative – 1 parameters. In this case, {0} will be replaced by the first parameter (negative) and {1} will be replaced by the second parameter (negative – 1). You can add as many items/parameters as you want, respecting the same principle

As you can see, adding 1 to 2,147,483,647 will result in a negative number, while subtracting 1 from -2,147,483,647 will result in a positive value. One of the dangers of the overflow is that you might often not notice the error, because the C# compiler will not warn you about the overflow exception. In other words, the program keeps running, even if the overflow exception occurs. That is why you have to be careful when using large numbers, because overflow exceptions can be hard to track.



Tags: , ,

Leave a Reply