Reputation: 17
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:
Upvotes: 0
Views: 194
Reputation: 526593
>>> "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.)
Upvotes: 1