Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
python:exceptions [2022/10/20 14:25] marclebrun créée |
python:exceptions [2022/10/20 14:37] (Version actuelle) marclebrun [Message] |
||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
====== Exceptions ====== | ====== Exceptions ====== | ||
+ | |||
+ | <code python> | ||
+ | try: | ||
+ | # exécuter ce code | ||
+ | except: | ||
+ | # s'il y a une exception de n'importe quel type | ||
+ | else: | ||
+ | # s'il n'y a aucune exception | ||
+ | </code> | ||
<code python> | <code python> | ||
Ligne 8: | Ligne 17: | ||
except Exception2: | except Exception2: | ||
# s'il y a une exception de type Exception2 | # s'il y a une exception de type Exception2 | ||
+ | except (Exception3, Exception4): | ||
+ | # s'il y a une exception de type Exception3 ou Exception4 | ||
else: | else: | ||
# s'il n'y a aucune exception | # s'il n'y a aucune exception | ||
Ligne 23: | Ligne 34: | ||
f.close() | f.close() | ||
</code> | </code> | ||
+ | |||
+ | ===== Message ===== | ||
+ | |||
+ | Certaines classes d'exceptions on un attribut **message** : | ||
+ | |||
+ | <code python> | ||
+ | try: | ||
+ | pass | ||
+ | except Exception as e: | ||
+ | print(e.message) | ||
+ | </code> | ||
+ | |||
+ | D'autres classes n'en ont pas et on peut utilise l'exception comme chaîne : | ||
+ | |||
+ | <code python> | ||
+ | try: | ||
+ | pass | ||
+ | except UnicodeDecodeError as e: | ||
+ | print(str(e)) | ||
+ | </code> | ||
+ | |||