简体   繁体   中英

How i can use “if” with exceptions on python?

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

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 .

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 except s:

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 Exception s unless you need that functionality for logging purposes.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM