如何捕获Python中finally异常块的消息?

2 投票
4 回答
3491 浏览
提问于 2025-04-16 20:02

我知道怎么捕捉异常并打印出它们返回的消息:

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e

到现在为止,这个方法很好用。

但是我想知道,怎么在'finally'块里捕捉并打印这个消息呢?

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e
finally:
    # What goes here? So I can see what went wrong?

从几个回答中我明白了,这似乎是不可能的。那么这样做可以吗?

class SelfDefinedException(Exception): pass

try:
    message = "Hello World!"
    raise SelfDefinedException(message)
except MyDefinedException, e:
    print "MyDefinedException", e
except Exception, e:
    # Hopefully catches all messages except for the one of MyDefinedException
    print "Unexpected Exception raised:", e

4 个回答

2

如果想要捕捉到任何类型的错误,可以使用:

try:
    foo()
except:
    print sys.exc_info()
    raise

但是,这几乎总是错误的做法。如果你不知道发生了什么类型的错误,那就没办法处理它了。如果真的发生了这种情况,你的程序应该直接关闭,并尽可能提供关于发生了什么的详细信息。

4

根据文档,你不能这样做:

在执行finally部分时,程序无法获取异常信息。

最好在except块中检查异常。

4

在finally块里的代码总是会被执行。你可以在catch块里查看出了什么问题。

撰写回答