Capture the last error

Hey.

When a script raises any error, blender pops a menu indicating the error type and the line where occurs.


My question is:
Is there any way to access that information from python?

What im trying to do is, capture that last error and jump to the line that error is indicating.

i was exploring the traceback and sys modules without luck.
sys.last_value returns the kind of error but not the line.

It would be great a feature like that.
Thanks.

Interesting question. Apparently you can use sys.exc_info(), which is described at http://docs.python.org/library/sys.html. The line numbers are in the traceback.tb_lineno variables. A little example shows how you can use it.

import sys

def test(n):
    m = 1/(n-3)
    print(n, m)
    return    

def testall(list):
    for n in list:
        try:
            test(n)
        except ZeroDivisionError as errmsg:
            print("ZeroDivisionError: %s" % errmsg)
        except Exception as errmsg:
            print("Unexpected error: %s" % errmsg)
            (type, value, traceback) = sys.exc_info()
            print("  type:", type)
            print("  value:", value)
            followTrace(traceback, 5)
    return 
    
def followTrace(traceback, depth):      
    if not traceback or depth < 0:
        return
    print("traceback:", traceback)
    print("  tb_frame:", traceback.tb_frame)
    print("  tb_lasti:", traceback.tb_lasti)
    print("  tb_lineno:", traceback.tb_lineno)
    print("  tb_next:", traceback.tb_next)
    followTrace(traceback.tb_next, depth-1)
    return

try:
    testall([1,2,3,4,"a"])
finally:
    print("Apparently necessary to delete circular references")
 

There is some warning that assigning the traceback to a local variable cause circular references which cannot be garbage-collected. The try-finally block takes care of that.

Hi Thomas!
Rather nice example!

Idea:
Maybe you put it somewhere in wiki.blender.org ?

Hi ThomasL.

Very nice example. Thanks for the answer.

What i can extract from that code is, that the frame is the “context” where the script executes and it only exists at runtime, so is the traceback objects.

sys.exc_info() returns None after the execution, so i dont know which is the error line after the execution. And thats what im trying to achieve.

Ill keep trying exploring the sys, traceback and inspect modules. Maybe i can find something like last traceback or last frame there.

The last error type is sys.last_value but thats not the info im looking for.


import traceback
    myfile = open("lasterrorinfo.txt", "w")
    traceback.print_stack(file = myfile)
    myfile.close()

This code prints the last error info to a file after execution, but only the errors where that code is written, not the one that we are running.

Cheers.