0

I need to manage python errors. For example when I type:

>>> 1/0

I give back:

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero

but I need to save this error in a variable. I use try..except for this:

>>> try:
    f(0)
except Exception as err:
    print(err)

and see in output:

division by zero

It's not enough for me. I need to error lines numbers like to IDLE (or other IDE) (I use python 3.3 and can't use python 2.7)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mshj
  • 101
  • 2

2 Answers2

2

Use the traceback module to extract specific information such as line numbers:

>>> try:
...     f(0)
... except Exception as err:
...     import traceback
...     traceback.print_last()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

You have saved the exception in a variable, err. It's still bound to the exception, even after the except block.

(The fact that print on an exception doesn't show all that much is a separate issue.)

However, it sounds like you wanted the traceback object, not just the exception object. That doesn't get automatically bound to a variable for you, but you can do it manually:

try:
    1/0
except Exception:
    exc_type, exc_value, exc_traceback = sys.exc_info()

See exc_info for more information.

But a traceback object is a pretty heavy thing, and keeps all kinds of other heavy things alive as long as you store it. One way to avoid carrying around an object as heavy and inter-linked as the traceback is to extract just the information you want from it. That's what the traceback module is for:

try:
    1/0
except Exception:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    exc_traceback = traceback.extract_tb(exc_traceback)

Now we're only carrying around a list of small tuples of strings and numbers, instead of the traceback object.

Or, even more simply, just format it immediately:

    exc_traceback = traceback.format_tb(exc_traceback)
abarnert
  • 354,177
  • 51
  • 601
  • 671