Reputation:
In python, I tried this code:
def divide(a=1, b=1):
try:
return a / b
except b == 0:
return 'Cannot divide by zero eg: %s / %s' % (a, b)
print(divide(1, 0))
and I got this error:
Traceback (most recent call last):
File "E:/Jethro/Coding/pythonProject2/main.py", line 8, in <module>
print(divide(1, 0))
File "E:/Jethro/Coding/pythonProject2/main.py", line 4, in divide
except b == 0:
TypeError: catching classes that do not inherit from BaseException is not allowed
Can anyone help?
Upvotes: 0
Views: 78
Reputation: 260570
This is not how try
/except
works. You need to define the exception(s) after except
:
def divide(a=1, b=1):
try:
return a / b
except ZeroDivisionError:
return 'Cannot divide by zero eg: %s / %s' % (a, b)
divide(1,0)
Alternatively, use a simple test on b
:
def divide(a=1, b=1):
if b==0:
return 'Cannot divide by zero eg: %s / %s' % (a, b)
else:
return a/b
divide(1,0)
Upvotes: 2