我怎么能写一个尝试/except块捕获所有异常?
当前回答
非常简单的例子,类似于这里发现的:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
如果您试图捕获所有异常,那么将所有代码放在“try:”语句中,而不是“print”执行可能抛出异常的操作。
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
在上面的例子中,你会看到这样的输出顺序:
1)执行可能引发异常的操作。
2) Finally在执行try语句后直接调用,无论是否抛出异常。
3)“抛出异常!”或“一切看起来都很好!”这取决于是否抛出异常。
希望这能有所帮助!
其他回答
try:
whatever()
except:
# this will catch any exception or error
值得一提的是,这不是正确的Python编码。这也将捕获您可能不想捕获的许多错误。
要捕获所有可能的异常,请捕获BaseException。它位于Exception层次结构的顶部:
Python 3: https://docs.python.org/3.10/library/exceptions.html#exception-hierarchy
Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
但正如其他人提到的,你通常不需要这个,只有在非常特定的情况下。
我刚刚发现了在Python 2.7中测试if异常名称的小技巧。有时我在代码中处理了特定的异常,所以我需要一个测试,看看这个名字是否在处理的异常列表中。
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
我添加了奖金方法,可以捕捉异常与完整的回溯,这可以帮助您了解更多的错误。
Python 3
import traceback
try:
# your code goes here
except Exception as e:
print(e)
traceback.print_exc()
您可以这样做来处理一般异常
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
推荐文章
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构