Sujet : Re: how to discover what values produced an exception?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 03. May 2024, 16:26:58
Autres entêtes
Organisation : Stefan Ram
Message-ID : <exceptions-20240503152349@ram.dialup.fu-berlin.de>
References : 1
Johanne Fairchild <
jfairchild@tudado.org> wrote or quoted:
How to discover what values produced an exception?
An exception isn't always tied to a value. I could, like, write:
if 3 > 2: "".call()
And I'd get an AttributeError exception. Can I now say the
values 3 and 2 caused this exception? Or was it the empty
string? Or the lack of a call method?
Let me try your example here: In the console:
|>>> ( 0, 0 )< 4
|TypeError: '<' not supported between instances of 'tuple' and 'int'
In this case, the values aren't important, one could even
say they're a distraction. What matters are the types of the
values, and those were given. However, the values are visible
in the console as they were typed in. In a script:
|Traceback (most recent call last):
| File "Main.py", line 1, in <module>
| ( 0, 0 )< 4
|TypeError: '<' not supported between instances of 'tuple' and 'int'
. Now I can see the offending line, which in this case even spills
the beans on the values.
Sometimes you really need those values. If they're values of global
names, you can kind of get them in the IDLE shell up to a point.
So I write this script in the IDLE editor and then run it:
a = 4
( 0, 0 )< a
. Now I get this in the IDLE console:
|Traceback (most recent call last):
| File "Main.py", line 2, in <module>
| ( 0, 0 )< a
|TypeError: '<' not supported between instances of 'tuple' and 'int'
. Then I can type
a
into the console, hit Return, and I see the value 4.
This script here has local variables, and that trick ain't
gonna fly no more:
def main():
a = 4
( 0, 0 )< a
main()
Now you got to add a debug print statement and run the script again.
def main():
a = 4
print( a )
( 0, 0 )< a
main()
In a bigger script there's all kinds of values and variables,
and sometimes the Python implementation can't know which ones
are critical for an exception, so the programmer's got to step
in and write those debug print statements.
(You could also use the IDLE debugger to see local variables,
but I prefer debug print statements.)