how to check overflow

how can i check if a sum of 2 numbers are causing an overflow

(but i want to use a custom exception, not the regular one).

thanks



Answer this question

how to check overflow

  • Makarand_Keer

    I guess the obvious way is to catch the exception that gets thrown when bounds checking is turned on, and then rethrow whatever you like. If I was going to do something like that, I'd make it a static method on a class, so I only had to write it once. Of course, any place you just plain add two numbers instead of calling this method, the behaviour you want will not occur. I don't think there's any way to change the exception that's defined for this.



  • Macy-Mike

    thanks for the help :)
  • DavidTM

    Assuming ints, how about:

     

    int delta = maxint – addend;

    if (delta < augend) {

                throw …;

    }



  • how to check overflow