views:

84

answers:

3

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?

+2  A: 
  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).
Amber
+5  A: 

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
juxstapose
+1  A: 

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
Wai Yip Tung