Python sauf mot- clé
Exemple
Si l'instruction génère une erreur, imprimez "Quelque chose s'est mal passé":
try:
x > 3
except:
print("Something went wrong")
Définition et utilisation
Le except
mot-clé est utilisé dans les blocs try...except. Il définit un bloc de code à exécuter si le bloc try génère une erreur.
Vous pouvez définir différents blocs pour différents types d'erreurs et des blocs à exécuter si tout va bien, voir les exemples ci-dessous.
Plus d'exemples
Exemple
Écrivez un message s'il s'agit d'une NameError, et un autre s'il s'agit d'une TypeError :
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
Exemple
Essayez d'exécuter une instruction qui génère une erreur, mais aucun des types d'erreur définis (dans ce cas, une ZeroDivisionError) :
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
Exemple
Écrivez un message si aucune erreur n'a été signalée :
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
Pages connexes
Le try
mot clé.
Le finally
mot clé.