Reputation: 190729
Consider this try
/except
block I use for checking error message stored in e
.
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?
Upvotes: 8
Views: 2895
Reputation: 18754
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
Upvotes: 3
Reputation: 3208
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
Upvotes: 10
Reputation: 526573
traceback
library.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
).Upvotes: 2