Python finally 子句中的异常吞掉之前的异常

3 投票
1 回答
2225 浏览
提问于 2025-04-17 17:15

在我的实际情况中,Segmentation fault(段错误)发生在finally这个部分,我对此无能为力,因为它是由一个通过ctypes使用的外部库引起的。其实,我对这个段错误并不在意,因为脚本反正已经完成了。

不过,这个段错误会吞掉在它之前发生的所有异常。这就导致我调试那个来自iDontExistNameError变得非常麻烦。这个错误根本找不到发生的地方。目前没有办法看到段错误之前抛出的任何异常。

def f1():
    try:
        while True:
            pass
    except KeyboardInterrupt:
        print iDontExist

if __name__=="__main__":
    try:
        f1()
    finally:
        raise Exception("segfault here")
        print "finally"

你觉得我该怎么处理这个问题?修复外部库不是一个选项。

1 个回答

4

你可以在 finally 之前尝试捕获异常:

try:
    f1()
except NameError as error:  # Change as needed
    print "Error caught:", error  # Or simply "raise", in order to raise the error caught
finally:
    raise Exception("segfault here")
    print "finally"

不过,abamert 说得对:段错误并不是一种异常,所以你可能需要找别的原因。

撰写回答