如果我事先不知道引发了什么类型的异常,我如何测试函数是否返回异常对象?
def func():
try:
bad_thing_happens # NameError("global name 'bad_thing_happens' is not defined",)
return True
except Exception as e:
return e
result = func()
if result == Exception:
print 'a bad thing happened'
Run Code Online (Sandbox Code Playgroud)
在这种情况下if语句返回False,我会错过该异常?
正确的方法是捕获函数之外的异常.例如:
def func():
bad_thing_happens
# NameError("global name 'bad_thing_happens' is not defined",)
return True
try:
result = func()
except NameError:
print("a bad thing happened")
Run Code Online (Sandbox Code Playgroud)
这使得异常来自(函数)的位置更加清晰,并避免了尝试返回异常的混乱 - 毕竟,异常通常意味着被捕获而不返回.
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |