如果lambda函数抛出异常,如何处理异常?

时间:2018-03-07 13:42:39

标签: python python-3.x lambda exception-handling anonymous-function

我不清楚当python lambda函数抛出异常时究竟发生了什么。

示例1

以下内容抛出了一个被零除的异常,这是预期的:

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

示例2

但是,如果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)

0 个答案:

没有答案