让我们考虑一种情况,在这种情况下,我会内置Exception
消息,并在处理消息时存储异常消息。我知道我可以按照以下示例中的两种方式进行操作。
try:
raise Exception('some message')
except Exception as e:
value_str = str(e)
value_args = e.args[0]
是否有理由认为一种方法优于另一种方法?
通常,使用str(e)
会更安全,因为在某些情况下e.args[0]
会引发索引错误:
try:
raise Exception()
except Exception as e:
value = e.args[0]
>>> IndexError: tuple index out of range
在某些情况下,第一个参数实际上不是消息,而str(e)
仅仅e.__str__()
是应始终返回消息的调用。
但是,在您的特定情况下,使用e.args[0]
似乎要快一些:
import timeit
def test_args():
try:
raise Exception('some message')
except Exception as e:
value = e.args[0]
def test_str():
try:
raise Exception('some message')
except Exception as e:
value = str(e)
print(timeit.timeit('test_args()', setup='from __main__ import test_args'))
print(timeit.timeit('test_str()', setup='from __main__ import test_str'))
>>> 0.5408027
>>> 0.5728966000000001
如果执行速度的这种最小提高很重要,并且您可以确定e
始终至少有一个参数,请使用e.args[0]
。在捕获特定类型的异常时,您还可以考虑直接访问属性。在所有其他情况下,我建议使用str(e)
。
有关从异常中检索信息的更多选项,请参见traceback
模块。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句