Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get better error information with try/except in Python

Consider this try/except 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?

like image 862
prosseek Avatar asked Sep 13 '10 01:09

prosseek


People also ask

How do you raise error in try-except in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Is it good practice to use try-except in Python?

The reason to use try/except is when you have a code block to execute that will sometimes run correctly and sometimes not, depending on conditions you can't foresee at the time you're writing the code.

How do you catch specific errors in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How do you use try-except for value error?

To resolve the ValueError in Python code, a try-except block can be used. The lines of code that can throw the ValueError should be placed in the try block, and the except block can catch and handle the error.


1 Answers

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
like image 99
eat_a_lemon Avatar answered Sep 26 '22 05:09

eat_a_lemon