How can I get better error information with try/ca

2020-05-27 08:04发布

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?

3条回答
地球回转人心会变
2楼-- · 2020-05-27 08:16

Like the first 2 answers, use traceback. Here is a more complete example.

import traceback

def foo():
    raise RuntimeError('we have a problem')

try:
    foo()
except:
    traceback.print_exc()

When you run it, you'll see

Traceback (most recent call last):
  File "C:\0\tmp\x.py", line 6, in <module>
    foo()
  File "C:\0\tmp\x.py", line 3, in foo
    raise RuntimeError('we have a problem')
RuntimeError: we have a problem
查看更多
闹够了就滚
3楼-- · 2020-05-27 08:20

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
查看更多
冷血范
4楼-- · 2020-05-27 08:37
  1. See the traceback library.
  2. If you want to just pass errors up the chain instead of modifying them, you can just use raise within an except block, which will then act like the except block isn't there (aside from any conditional logic/side effects you may have done before the raise).
查看更多
登录 后发表回答