How can I detect integer overflow on 32 bits int?

前端 未结 5 1332
逝去的感伤
逝去的感伤 2020-12-03 06:33

I know such topic was asked several times, but my question is about overflow on full 32 bits of int. For example:

  11111111111111111111111         


        
5条回答
  •  孤城傲影
    2020-12-03 07:25

    Math.addExact throws exception on overflow

    Since Java 8 there is a set of methods in the Math class:

    • toIntExact(long)
    • addExact(int,int)
    • subtractExact(int,int)
    • multiplyExact(int,int)

    …and versions for long as well.

    Each of these methods throws ArithmeticException if overflow happens. Otherwise they return the proper result if it fits within the range.

    Example of addition:

    int x = 2_000_000_000;
    int y = 1_000_000_000;
    try {
        int result = Math.addExact(x, y);
        System.out.println("The proper result is " + result);
    } catch(ArithmeticException e) {
        System.out.println("Sorry, " + e);
    }
    

    See this code run live at IdeOne.com.

    Sorry, java.lang.ArithmeticException: integer overflow

提交回复
热议问题