如何在Python中使用try / catch获取更好的错误信息 [英] How can I get better error information with try/catch in Python

查看:758
本文介绍了如何在Python中使用try / catch获取更好的错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



尝试/抓住获取 e



  queryString =SELECT * FROM benchmark WHERE NOC = 2
try:
res = db.query(queryString)
除了SQLiteError,e:
#`e`有错误信息
print`e`

这里的 e 对象只包含上面的字符串。然而,当python报告一个未处理的错误,它显示一个相当详细的信息如下:

 
追溯(最近的最后一次呼叫):
文件fool.py,第1行,
打开(abc.zyz,r)
IOError:[Errno 2]没有这样的文件或目录:'abc.zyz'

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

解决方案

这将显示错误的追踪。

  import traceback 

try:
res = db.query(queryString)
除了SQLiteError,e:
#`e`有错误信息
print`e`
for tb在traceback.format_tb( sys.exc_info()[2]):
打印tb


Consider this try/catch block I use for checking error message stored in e.

Try/Catch to get the e

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

The e object here contains nothing more than the above string. When python reports an unhandled error, however, it shows a pretty detailed info as below:

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'

My question is, how can I get the information such as above (the file and the line number etc.)? Or, if e contains this info, how is it stored inside it?

解决方案

This will show the trace to the error.

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

这篇关于如何在Python中使用try / catch获取更好的错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆