Exceptions

Python ↔ Baobab
12 correspondences

essayer/attraper/enfin translate try/except/finally, lever translates raise. Standard errors have French names: ErreurValeur for ValueError, etc.

PythonBaobabDescription
try:essayer:Guarded block.
except ValueError as e:attraper ErreurValeur comme e:Catch a specific error type.
except Exception:attraper Erreur:Catch any error.
finally:enfin:Always executed, error or not.
raise ValueError("msg")lever ErreurValeur("msg")Raise an error on purpose.
ValueErrorErreurValeurInvalid value (e.g. entier("abc")).
TypeErrorErreurTypeOperation on an incompatible type.
IndexErrorErreurIndiceIndex out of a sequence's bounds.
KeyErrorErreurCleMissing dictionary key.
ZeroDivisionErrorErreurDivisionZeroDivision by zero.
FileNotFoundErrorErreurFichierIntrouvableFile missing when opening.
class MonErreur(Exception):classe MonErreur(Erreur):Custom error via inheritance.
Complete example — Baobab ↔ Python
Baobab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fonction diviser(a, b): si b == 0: lever ErreurValeur("b ne peut pas être zéro") retourner a / b essayer: afficher(diviser(10, 2)) # → 5.0 afficher(diviser(1, 0)) # lève l'erreur attraper ErreurValeur comme e: afficher(f"Problème : {e}") attraper Erreur: afficher("Autre erreur inattendue") enfin: afficher("Calcul terminé") # toujours exécuté essayer: notes = {"maths": 15} afficher(notes["chimie"]) attraper ErreurCle: afficher("Matière inconnue")
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def diviser(a, b): if b == 0: raise ValueError("b ne peut pas être zéro") return a / b try: print(diviser(10, 2)) # → 5.0 print(diviser(1, 0)) # raises the error except ValueError as e: print(f"Problème : {e}") except Exception: print("Autre erreur inattendue") finally: print("Calcul terminé") # always executed try: notes = {"maths": 15} print(notes["chimie"]) except KeyError: print("Matière inconnue")