我有一个python文件,其中有两个函数,每个函数都会引发异常。
def f():
raise e1
def g():
raise e2
我的问题是,是否可以将这些异常存储在一个变量中,例如list --e1,e2--,以便控制另一个函数中异常执行的顺序,例如h?
发布于 2018-07-31 21:08:59
异常是对象,就像Python中的大多数对象一样;具体地说,您可以在捕获时将其绑定到名称,然后将其添加到列表中。例如:
exceptions = []
try:
f()
except Exception as f_exc:
exceptions.append(f_exc)
try:
g()
except Exception as g_exc:
exceptions.append(g_exc)
我不确定您脑海中的用例是什么,您想要存储异常以便稍后查看。通常,一旦捕获到异常,就会立即对其执行操作。
发布于 2018-07-31 21:21:11
正如切普纳指出的,异常是对象。如果您以后想以相同的顺序处理它们(甚至可能是不同的Thread),您应该将它们存储在队列中:
import Queue
exceptions = Queue.Queue()
try:
f()
except Exception as e:
exceptions.put(e)
然后,您可以让另一个线程访问相同的变量exceptions
并处理(或记录)它们:
while True:
while not exceptions.empty():
do_sth_with_exception(exceptions.get())
https://stackoverflow.com/questions/51614117
复制相似问题