我不清楚当python lambda函数抛出异常时究竟发生了什么。
以下内容抛出了一个被零除的异常,这是预期的:
码try:
bar = lambda : 1/0
x = bar()
except Exception as e:
bottle = str(e)
msg = bottle.lstrip('\n')
msg = msg.lstrip('\r')
msg = msg.lstrip('\n') ## in case \r was first, then \n
msg = msg.lstrip(' ')
msg = "Aye! tings be workin' correctly. An exception were thrown. " + msg
print(msg)
产量
Aye! tings be workin' correctly. An exception were thrown. division by zero
但是,如果lambda函数是在另一个函数内定义和调用的,那么尝试捕获异常并不能按预期工作
码try:
def f1():
print("A")
f3 = lambda : 1/0
print("B")
f3()
print("C")
print("\nIf you're reading this, no exception was thrown.")
except Exception as e:
msg = str(e)
raise e(msg)
产量
If you are reading this, no exception was thrown.
OS : Windows
IDE : Spyder 3.2.7
Python : 3.6.4 32bit
Qt : 5.9.3
PyQt5 : 5.9.2
IPython >=4.0 : 6.2.1 (OK)
jedi >=0.9.0 : 0.11.1 (OK)
nbconvert >=4.0 : 5.3.1 (OK)
qtconsole >=4.2.0: 4.3.1 (OK)
rope >=0.9.4 : 0.10.7 (OK)
sphinx >=0.6.6 : 1.7.1 (OK)