+ 1
How we use standard exception(in c++) ,overflow of int data type ?
Suppose i have the following code: int a=1234234234; //a is not in range of integer data-type which cause warning //how we use standard exception in in the above case. // plz write a small exception handling code
4 Answers
+ 3
If the number is too large and you see a warning, you don't need code to fix the problem. Just change it to `long` or a smaller number.
The number you wrote there will never change unless you change it, and then compile again. You don't need code that checks at runtime if the number is too large, since the error will already be caught at compile time.
The "exception handling" is you, the prgrammer, fixing the problem in code.
+ 2
Just use initializer lists for initialization instead of the assignment operator.
`int a{ 12345654321 };`
The above line gives a compile time error.
This however will only work when you're initializing the variable. For the other cases, you can refer to this
https://www.embeddedrelated.com/showarticle/532.php
(Side note: the number in your question is a valid integer and does not give warning)
+ 2
Well yeah and the exception happens at compile time, so runtime checks are unneccessary.
If you are talking about overflow in general, like, how do you know whether `a+b` overflowed, given large numbers `a` and `b`, there is no easy answer.
For `c = a+b` you could check whether `c < a || c < b`, if you know that both numbers are positive. If true, you know an overflow occurred.
But this check already fails for multiplication.
Some CPUs have an overflow register that is set to 1 whenever an overflow happens, but there is no real way to read it's value in C++ and then again, some CPUs don't even have one.
In any case, overflows in C++ don't produce exceptions and usually you won't know it happened until your program produces garbage output. If you know you will be using large numbers in your code and may run the risk of overflowing, you should switch to longs, or doubles, or even bigints that can hold arbitrarily large numbers.
0
Guys, the main topic is exception handling in this case