如何在Python中使用try/catch获得更好的错误信息

pro*_*eek 8 python error-handling

考虑我用来检查存储的错误消息的try/catch块e.

尝试/抓住以获得 e

queryString = "SELECT * FROM benchmark WHERE NOC = 2"
try:
    res = db.query(queryString) 
except SQLiteError, e:
    # `e` has the error info 
    print `e`
Run Code Online (Sandbox Code Playgroud)

e这里的对象只包含上面的字符串.但是,当python报告未处理的错误时,它会显示一个非常详细的信息,如下所示:

Traceback (most recent call last):
  File "fool.py", line 1, in 
    open("abc.zyz", "r")
IOError: [Errno 2] No such file or directory: 'abc.zyz'

我的问题是,如何获取上述信息(文件和行号等)?或者,如果e包含此信息,它是如何存储在其中的?

eat*_*mon 10

这将显示错误的跟踪.

import traceback

try:
    res = db.query(queryString) 
except SQLiteError, e:
    # `e` has the error info 
    print `e`
    for tb in traceback.format_tb(sys.exc_info()[2]):
        print tb
Run Code Online (Sandbox Code Playgroud)