Division by Zero

edited December 2014 in Programming Questions

Hi,

In a program I had a Division By Zero due to a bug in my program. Butr the programn does not Stop, but the variable had an undefined state. Is there any possibility to get an exepion when an "division by zero" occurs? The rsulting float could not be compared to null, is there any chance to recognice the incorrexct state of a resulting value?

Thank you for your help

Answers

  • some code would help.

    Often you could check before dividing:

    if (someVariable != 0) {
        result = something / someVariable;
    }
    
  • The result will be Infinity with floats

  • Can I check a variable whether it is infinity or not? something like: if (someVariable==infinity) { ..somecode... }

    Currently I solved the bug by chekcing for the "Zero situation", but I like to get a more robust code by checking the variable before accessing it, whether there is a usable value set.

  • Is there any possibility to get an exepion when an "division by zero" occurs?

    An ArithmeticException is thrown when you attempt to divide by zero (integers) but because this exception is a runtime-exception there is no requirement to catch it but you can if you wish e.g.

    int a = 10;
    int b = 0;
    
    try {
      c = a/b;
    }
    catch(ArithmeticException e){
      println("Attempt to divide by zero");
    }
    

    It is unrealistic to do this for every integer division just as it is unrealistic to test the divisor == 0. You would only do one of these if is there was a realistic chance of getting division-by-zero.

  • Here, the code below should do it. There also is NEGATIVE_INFINITY to look out for (not sure if it is relevant to you):

    void setup() {
      size(100, 100);
    
      float a = 1.0;
      println(isInfinity(a));
      a /= 0.0;
      println(isInfinity(a));
    
      exit();
    }
    
    boolean isInfinity(float in) {
      return in == Float.POSITIVE_INFINITY;
    }
    
  • Thank you all, this will help me a lot.

Sign In or Register to comment.