[英]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?如果错误是 ZeroDivisionError,我该怎么做,我的程序会打印“lol”? My programms print(Exception), even if errors is ZeroDivsionError我的程序打印(异常),即使错误是 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.但是,我建议只明确捕获ZeroDivisionError
。
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
. except
子句按顺序检查,因此如果引发其他异常,它将首先无法匹配ZeroDivisionError
,然后才能成功匹配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. Exception == ZeroDivisionError
正在比较这两个类是否相同。 They aren't though, so that will always result in False
.他们不是,所以这总是会导致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:有两个except
会更好:
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.尽管在大多数情况下,您不想捕获所有Exception
,除非您需要该功能来进行日志记录。
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.但是,您不应该只捕获“所有”异常,因此最好省略第二部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.