我怎么能写一个尝试/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)“抛出异常!”或“一切看起来都很好!”这取决于是否抛出异常。
希望这能有所帮助!
其他回答
首先,有些异常是您希望它们破坏您的代码的(因为当这个错误发生时,您的代码无论如何都不能正常工作!),还有一些异常是您希望以静默/平滑的方式捕获的。试着求微分。您可能不想捕获所有的异常!
其次,不必捕获所有内容,您可以花时间查看流程的日志。假设您正在获得一个不同的/第三方异常,例如来自像GCP这样的云服务提供商。在日志中,您可以找到正在获得的异常。然后,你可以这样做:
from google.api_core.exceptions import ServiceUnavailable, RetryError
for i in range(10):
try:
print("do something")
except ValueError:
print("I know this might happen for now at times! skipping this and continuing with my loop"
except ServiceUnavailable:
print("our connection to a service (e.g. logging) of gcp has failed")
print("initializing the cloud logger again and try continuing ...")
except RetryError:
print("gcp connection retry failed. breaking the loop. try again later!)
break
对于其余的(可能发生或不可能发生的错误),我为代码在遇到意外异常时崩溃留下了空间!这样我就可以理解发生了什么,并通过捕获边缘情况来改进我的代码。
如果你想让它永远不会因为某些原因崩溃,例如,如果它是嵌入在远程硬件中的代码,你不容易访问,你可以在最后添加一个通用的异常捕获器:
except Exception as e:
print(f"something went wrong! - {e}")
您还可以在这里查看Python 3的异常层次结构。Exception和BaseException的区别在于,Exception不会捕获SystemExit, KeyboardInterrupt或GeneratorExit
我添加了奖金方法,可以捕捉异常与完整的回溯,这可以帮助您了解更多的错误。
Python 3
import traceback
try:
# your code goes here
except Exception as e:
print(e)
traceback.print_exc()
非常简单的例子,类似于这里发现的:
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)“抛出异常!”或“一切看起来都很好!”这取决于是否抛出异常。
希望这能有所帮助!
除了一个裸露的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:如果你捕获并吞下了它们,那么任何人都很难退出你的脚本。
要捕获所有可能的异常,请捕获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))
但正如其他人提到的,你通常不需要这个,只有在非常特定的情况下。
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?