关于捕获任何异常 [英] About catching ANY exception
本文介绍了关于捕获任何异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我该如何写一个 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
这篇关于关于捕获任何异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文