如何编写一个捕获所有异常的 `try`/`except` 块? [英] How can I write a `try`/`except` block that catches all exceptions?
本文介绍了如何编写一个捕获所有异常的 `try`/`except` 块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写一个try
/except
块来捕获所有异常?
How can I write a try
/except
block that catches all exceptions?
推荐答案
你可以,但你可能不应该:
You can but you probably shouldn't:
try:
do_something()
except:
print("Caught it!")
但是,这也会捕获像 KeyboardInterrupt
这样的异常,而您通常不希望那样,对吗?除非您立即重新提出异常 - 请参阅以下示例来自文档:
However, this will also catch exceptions like KeyboardInterrupt
and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
这篇关于如何编写一个捕获所有异常的 `try`/`except` 块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文