Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cause an exception on integer overflow? [duplicate]

Tags:

java

exception

If I divide by zero I get a java.lang.ArithmeticException, as in this example :

int a = 3/0;

I'd like to make it so that an integer overflow also causes an Exception. So the following program would throw an exception rather than printing -2147483648.

public static void main(String[] args) {
    int a = Integer.MAX_VALUE + 1;
    System.out.println( a );
}

I know I could use BigInteger, which does not overflow and is only limited by available memory.

I know I could make my own add function which checks for overflows. Or I could use Java 8 Math.addExact.

I realize I am asking for behaviour contrary to JLS at 15.18.2

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

Besides modifying the source of a JVM and using such modified JVM. Is there any way to acomplish this? And even modifying the source of the JVM would not be enough, because libraries could depend on that behaviour and I don't want them to be affected by this, only my code.

like image 555
Anonymous Coward Avatar asked Aug 07 '16 09:08

Anonymous Coward


People also ask

What can we do to avoid overflow errors if we need to deal with large numbers?

look into bignum arithmetic libraries. they'll be a bit slower than standard C arithmetic but at least you won't get overflow. also many standard math functions (exp etc) will set errno to ERANGE in case of overflow. Usually, it is prevented by thinking carefully when writing code.

What causes integer overflow?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

Does Java language handle the overflow in its program?

Java doesn't do anything with integer overflow for either int or long primitive types and ignores overflow with positive and negative integers.


1 Answers

I am sorry to say that, but you can not.

The only solution would be to write your own function or use Math#addExact, as you said.

like image 57
Fabian Damken Avatar answered Sep 22 '22 15:09

Fabian Damken