0

I have code like this:

    a = 0
try:
    b = 2/a
    print(b)
except Exception:
    if (Exception == ZeroDivisionError):
        print("lol")
    else:
        print(Exception)

How I can do, that my programms print "lol" if error is ZeroDivisionError? My programms print(Exception), even if errors is ZeroDivsionError

3 Answers 3

2

You have to bind the caught exception to a name first.

a = 0
try:
    b = 2 / a
    print(b)
except Exception as exc:
    if isinstance(exc, ZeroDivisionError):
        print("lol")
    else:
        print(exc)

However, I would recommend just catching a ZeroDivisionError explicitly.

try:
    b = 2 / a
    print(b)
except ZeroDivisionError;
    print("lol")
except Exception as exc:
    print(exc)

except clauses are checked in order, so if some other exception is raised, it will first fail to match against ZeroDivisionError before successfully matching against Exception.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!
1

You're testing the exceptions incorrectly. Your code isn't checking what exception is thrown.

Exception == ZeroDivisionError is comparing if those two classes are the same. They aren't though, so that will always result in False. You want something closer to:

try:
    b = 2/0
    print(b)
except Exception as e:  # e is the thrown exception
    if isinstance(e, ZeroDivisionError):
        print("lol")
    else:
        print(Exception)

Doing manual type checks like this isn't great though if it can be helped. This would be better by having two excepts:

try:
    b = 2/0
    print(b)
except ZeroDivisionError:
    print("lol")
except Exception:
    print(Exception)

Although, in most cases, you don't want to catch all Exceptions unless you need that functionality for logging purposes.

Comments

0

You could do like this

a = 0
try:
    b = 2/a
    print(b)
except ZeroDivisionError:
    print("lol")
except Exception as e:
    print(e)

However, you should not just catch "all" exceptions, so it is better to leave out the second part.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.