Lire les erreurs
Qu’est-ce c’est ?
L’erreur apparait au moment où l’instruction erronée est exécutée dans le cours du programme.
A priori, l’apparition d’une erreur interrompt le programme immédiatement -> plantage.
(il est quand même possible de gérer les exceptions)
Les informations fournies par une erreur
le type d’erreur
le message d’erreur
la ligne de code en jeu
la pile d’appel -> traceback
Coder == Débugger, autant utiliser l’information qu’on nous donne.
Exemples classiques d’erreurs
NameError
[1]:
nexistepas
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[1], line 1
----> 1 nexistepas
NameError: name 'nexistepas' is not defined
ZeroDivisionError
[2]:
2 / 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[2], line 1
----> 1 2 / 0
ZeroDivisionError: division by zero
TypeError
[3]:
'un' + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 1
----> 1 'un' + 2
TypeError: can only concatenate str (not "int") to str
IndexError
[4]:
hey = 'bonjour'
hey[9]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[4], line 2
1 hey = 'bonjour'
----> 2 hey[9]
IndexError: string index out of range
KeyError
[5]:
foobar={'un': 1}
foobar['deux']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[5], line 2
1 foobar={'un': 1}
----> 2 foobar['deux']
KeyError: 'deux'
Traceback et imbrication d’appels
La Traceback permet de suivre l’imbrication des appels au moment de l’erreur.
[6]:
def f0(x):
return x / 0
def f1(x):
return f0(x) / 1
def f2(x):
return f1(x) / 2
def f3(x):
return f2(x) / 3
f3(1)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[6], line 13
10 def f3(x):
11 return f2(x) / 3
---> 13 f3(1)
Cell In[6], line 11, in f3(x)
10 def f3(x):
---> 11 return f2(x) / 3
Cell In[6], line 8, in f2(x)
7 def f2(x):
----> 8 return f1(x) / 2
Cell In[6], line 5, in f1(x)
4 def f1(x):
----> 5 return f0(x) / 1
Cell In[6], line 2, in f0(x)
1 def f0(x):
----> 2 return x / 0
ZeroDivisionError: division by zero