Find last attempted instruction before exception

2944 views python
4

I am trying to find out which was the last attempted instruction that triggered an exception, e.g. a TypeError.

Let's consider this example.

def test(value1, value2):
    print("Hello" + value1 + value2)

If this function is called with:

test("World!", 5)
test(5, "World!")

I will get a TypeError in both cases. However, in the first execution the last statement that wil be attempted (and triggers the error) is "Hello" + value1. In the second execution it would be "Hello World!" + value2. At least this is my assumption, that Python executes both separately, since they are "calls" to the add operator?

The error message will be the same both times though. Saying:

...
    print("Hallo" + value1 + value2)
TypeError: must be str, not int

Can I find out what the last executed statement was that triggered the TypeError?

answered question

do you try debug a code ?

No, it is part of attempting to build something like a dynamic type inferencer.

no you can't unless you resolve the adds separately

Doesn't Python at the Bytecode level execute both adds separately? And shouldn't the add that caused the error be last line (or maybe not show up at all) in the stacktrace?

1 Answer

12

Your IDE will generally tell you which line raised the TypeError. I'm using PyCharm which says:

Traceback (most recent call last):
File "C:/Users/CarlS/PycharmProjects/Test/test.py", line 3, in <module>
test("World!", 5)
File "C:/Users/CarlS/PycharmProjects/Test/test.py", line 2, in test
print("Hello" + value1 + value2)
TypeError: can only concatenate str (not "int") to str

Here we can see that line 3 triggered the error and failed during the execution in line 2. Thus, from my code I know that the test('World!', 5) raised the error.

posted this

Have an answer?

JD

Please login first before posting an answer.