【问题标题】:How to get detailed exception?如何获得详细的异常?
【发布时间】:2019-01-18 10:12:31
【问题描述】:

我经常在python异常中这样做:

try:
    <some process>
except Exception as e:
    print(e)

当我希望脚本继续运行但仍然告诉我有错误时,这对我很有帮助。但是,print(e) 并不像我提出异常那样详细。有没有办法在不引发异常的情况下更详细地显示错误?

【问题讨论】:

标签: python python-3.x exception-handling


【解决方案1】:

有多种方法可以打印回溯信息。

如 cmets 中所述,您可以使用 traceback 模块的 print_exc 函数

try:
    1 / 0
except Exception:
    traceback.print_exc()

Traceback (most recent call last):
  File "exes.py", line 10, in <module>
    1 / 0
ZeroDivisionError: division by zero

如果您使用日志记录模块,logging.exception 函数将自动将回溯记录为错误级别日志消息的一部分。

try:
    2 / 0 
except Exception:
    logging.exception('Something went wrong')

ERROR:root:Something went wrong
Traceback (most recent call last):
  File "exes.py", line 15, in <module>
    2 / 0
ZeroDivisionError: division by zero

如果您希望在不同的日志级别记录回溯,可以将exc_info=True 传递给日志函数以记录回溯。

try:
    3 / 0 
except Exception:
    logging.warning('Something went wrong.', exc_info=True)

WARNING:root:Something went wrong.
Traceback (most recent call last):
  File "exes.py", line 20, in <module>
    3 / 0
ZeroDivisionError: division by zero

【讨论】:

  • 非常感谢。这对我真的很有帮助
猜你喜欢
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
相关资源
最近更新 更多