maxymoo
maxymoo

Reputation: 36545

Can you bring Python debugger back to the original exception during custom exception handling?

My code is raising a custom exception which is putting my debugger in the wrong place. For example in the following code, I would like to print the value of my important_local_variable from the debugger, however it seems to be inaccessable as the debugger is starting inside the CustomException:

test.py

class CustomException(Exception):
    pass

def my_func():
    important_local_variable = 0
    badness = 1/important_local_variable

try:
    my_func()
except:
    raise CustomException
python3 -m ipdb test.py
bash-3.2$ python3 -m pdb test.py
> /Users/max/test.py(1)<module>()
-> class CustomException(Exception):
(Pdb)

Upvotes: 1

Views: 133

Answers (2)

HPKG
HPKG

Reputation: 345

Yes it is trying to define the exception class. You should let the debugger continue.

As per comment, it is the first line of the script.

Also even if you had a main function, the python control will start from first statement of module.

Upvotes: 1

Randy
Randy

Reputation: 14849

You may just need to adjust which stack frame you're in with u and d in pdb. In your toy example, once the ZeroDivisionError hits, you can go down into the function and pull out the local variable just fine:

C:\Users\Randy\test>python -m pdb test.py
> c:\users\randy\test\test.py(1)<module>()
-> class CustomException(Exception):
(Pdb) n
> c:\users\randy\test\test.py(4)<module>()
-> def my_func():
(Pdb) n
> c:\users\randy\test\test.py(8)<module>()
-> try:
(Pdb) n
> c:\users\randy\test\test.py(9)<module>()
-> my_func()
(Pdb) n
ZeroDivisionError: division by zero
> c:\users\randy\test\test.py(9)<module>()
-> my_func()
(Pdb) d
> c:\users\randy\test\test.py(6)my_func()
-> badness = 1/important_local_variable
(Pdb) important_local_variable
0

If it's the initial

> c:\users\randy\test\test.py(1)<module>()
-> class CustomException(Exception):

that was concerning you, that's just the interpreter running the code from the start, not the exception being triggered. This happens since we started pdb from the beginning of the program. You just need to step through the code with n until the errors start actually being thrown, as I did in the example above.

Upvotes: 1

Related Questions