1.2 KiB
1.2 KiB
Exercices sur les exceptions
Exercice 1
- Écrivez un bloc
try/except - Dans le bloc
try, provoquez une division par zéro (ZeroDivisionError) - Dans le bloc
except, affichez "Division impossible !"
Exercice A1
- Générez un nombre entier aléatoire entre 0 et 1 :
from random import randint
number = randint(0, 1)
- Écrivez un bloc
try/except - Dans le bloc
try:- Si
numbervaut0, afficher[1, 2, 3][4](IndexError) - Si
numbervaut1, afficher{}[0](KeyError)
- Si
- Écrire un bloc
exceptpourIndexError, qui affiche "Erreur d'index" - Écrire un bloc
exceptpourKeyError, qui affiche "Erreur de clé"
Exercice A2 (variante)
- Reprenez une copie de l'exercice 1
- Mais cette fois, ayez un seul bloc
exceptqui gère à la foisIndexErroretKeyError, et qui affiche "Erreur d'accès".
Exercice A3
- Écrivez un bloc
try/except - Provoquez une erreur dans le bloc
try(pas une erreur de syntaxe !) - Écrivez un bloc
exceptqui ne gère pas la bonne erreur (ex.IOError) - Écrivez un bloc
finallyqui affiche du texte - Exécutez votre code et voyez que le bloc
finallyest bien honoré.