0

I am trying to handle a divide by zero exception manually in python3.5, however, it keeps ignoring my user defined case and giving the default exception. How can I avoid this? Any help is appreciated.

NOTE: I'm using a list as a stack, hence the last and is checking whether the top elem is 0. Also, the order is correct - I deliberately take the top elem as denominator

elif 'div' in command:
        if len(stack)!=0 and len(stack)!=1 and is_digit(stack[len(stack)-2]) and is_digit(stack[len(stack)-1]) and stack[len(stack)-1]!=0:
            op2 = stack.pop();
            op1 = stack.pop();
            stack.append(str( int(int(op1) / int(op2)) ) + '\n');
        else:
            stack.append(':error:\n');

This gives ZeroDivisionError: division by zero INSTEAD of :error:

J. Doe
  • 17
  • 4

1 Answers1

1
>>> "0" == 0
False

Your if statement tests for equality to 0, but you don't convert to an int until you're doing the calculation, so your != test is always going to pass as it's comparing a string against an integer.

(This is assuming your stack inputs are strings; if they aren't then you probably don't need the int() calls - but the fact that you're adding the result of the division to the stack as a string leads me to believe that they are.)

Amber
  • 507,862
  • 82
  • 626
  • 550
  • Thanks a lot! Even though I tried doing the comparison with "0" initially, it didn't work. However, your answer led me to typecast stack[len(stack)-1] to int which worked perfectly – J. Doe Mar 14 '17 at 21:31
  • It's possible it was `"0\n"`, and thus `"0\n"`would not compare equal to `"0"`. – Amber Mar 15 '17 at 00:09