I have a few lines of code that I need to execute via exec() and I would like to know which line is rising ZeroDivisionError.
Here an example:
code = \
'''
a = 9
b = 0
c = a/b
print(c)
'''
>>>exec(code)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-3-00bada8e7a44> in <module>()
5 print(c)
6 '''
----> 7 exec(code)
<string> in <module>()
ZeroDivisionError: division by zero
This is fine, but I would like to have c = a/b
instead of exec(code)
as argument of the exception as it occurs for other types of error:
code = \
'''
a = 9
b = 0
c === b
print(c)
'''
>>>exec(code)
File "<string>", line 4
c === b
^
SyntaxError: invalid syntax
In this case, SyntaxError
is pointing directly to the line responsible for the error.
Why this difference?
How can I get ZeroDivisionError
pointed correctly?
UPDATE
I have tried the "compile()
solution" suggested by Schore but it did not work as expected in my case:
code = \
'''
a = 9
b = 0
c = a/b
print(c)
'''
z = compile(code, "", "exec")
>>>exec(z)
ZeroDivisionError Traceback (most recent call last)
<ipython-input-8-857f94e79b67> in <module>()
6 '''
7 z = compile(code, "", "exec")
----> 8 exec(z)
? in <module>()
ZeroDivisionError: division by zero