我怎么能写一个尝试/except块捕获所有异常?
当前回答
您可以这样做来处理一般异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
其他回答
除了一个裸露的except:子句(其他人说你不应该使用它),你可以简单地捕获Exception:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
您通常只考虑在代码的最外层这样做,例如,如果您想在终止之前处理任何其他未捕获的异常。
except Exception相对于bare except的优点是,它不会捕获一些异常,最明显的是KeyboardInterrupt和SystemExit:如果你捕获并吞下了它们,那么任何人都很难退出你的脚本。
我刚刚发现了在Python 2.7中测试if异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要一个测试,看看这个名字是否在处理的异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
你可以,但你可能不应该:
try:
do_something()
except:
print("Caught it!")
然而,这也会捕获像KeyboardInterrupt这样的异常,你通常不希望那样,对吗?除非你马上重新抛出异常-请参阅下面的文档示例:
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:
whatever()
except:
# this will catch any exception or error
值得一提的是,这不是正确的Python编码。这也将捕获您可能不想捕获的许多错误。
您可以这样做来处理一般异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录