Python当我捕获异常时,如何获取类型,文件和行号?

问题:

捕获将打印如下的异常:

Traceback (most recent call last):
  File "c:/tmp.py", line 1, in <module>
    4 / 0
ZeroDivisionError: integer division or modulo by zero

我想将其格式化为:

ZeroDivisonError, tmp.py, 1

回答:

import sys, os

try:
    raise NotImplementedError("No error")
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    print(exc_type, fname, exc_tb.tb_lineno)

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Python When I catch an exception, how do I get the type, file, and line number?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

+ 48 = 52