Reputation:
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
Upvotes: 0
Views: 112
Reputation: 66
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.
Upvotes: 0
Reputation: 45745
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.
Upvotes: 1
Reputation: 531055
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
.
Upvotes: 2