8. Erreurs et Exceptions

try/except/else/finally, raise, chaînage, exceptions personnalisées, assert.


8.1 Syntaxe de base

try:
    x = int("abc")
except ValueError:
    print("Conversion impossible")

8.2 Multiples exceptions

try:
    ...
except ValueError:
    ...
except (TypeError, RuntimeError) as e:
    print(f"Erreur: {e}")

8.3 else et finally

try:
    fichier = open("data.txt")
    contenu = fichier.read()
except FileNotFoundError:
    print("Fichier absent")
else:
    print("Lu avec succès")  # exécuté si pas d'exception
finally:
    fichier.close()          # toujours exécuté

8.4 raise

raise ValueError("Message d'erreur")
raise  # relance l'exception courante

Chaînage :

try:
    ...
except OSError as e:
    raise RuntimeError("Échec réseau") from e

8.5 Exceptions personnalisées

class MonErreur(Exception):
    """Exception spécifique à mon application."""
    pass
 
raise MonErreur("Quelque chose a mal tourné")

Avec attributs :

class ValidationError(Exception):
    def __init__(self, champ: str, valeur: object):
        self.champ = champ
        self.valeur = valeur
        super().__init__(f"{champ} invalide: {valeur}")
 
raise ValidationError("âge", -5)

8.6 Hiérarchie commune

BaseException
├── SystemExit
├── KeyboardInterrupt
└── Exception
    ├── StopIteration
    ├── ArithmeticError (ZeroDivisionError, OverflowError)
    ├── LookupError (IndexError, KeyError)
    ├── OSError (FileNotFoundError, PermissionError)
    ├── ValueError
    ├── TypeError
    ├── RuntimeError
    └── ...

Attraper Exception (pas BaseException) :

try:
    ...
except Exception:  # n'attrape pas KeyboardInterrupt, SystemExit
    ...

8.7 assert

assert x > 0, f"x doit être positif, reçu {x}"

Lève AssertionError si la condition est fausse. Désactivée avec python -O.

8.8 Contexte avec try/except/raise

def diviser(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Division par zéro")
    return a / b
 
try:
    resultat = diviser(10, 0)
except ValueError as e:
    print(f"Erreur: {e}")

🔗 ← Retour au cours · ← précédent · Suivant →