user17587785
user17587785

Reputation:

When I try to use an exception to catch Division by Zero, it still gives me an error?

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

Answers (1)

mozway
mozway

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

Related Questions