En bref. Une exception détourne le flux. C’est utile quand l’appelant ne peut rien y faire sur place, et du gaspillage quand l’échec est prévu.
Le modèle en une phrase
Lève pour l’imprévu, rends une valeur pour l’attendu. Si tu rattrapes là où tu lèves, c’est un
ifdéguisé.
In short. An exception diverts the flow. It’s useful when the caller can do nothing on the spot, and wasteful when the failure is expected.
The model in one sentence
Raise for the unexpected, return a value for the expected. If you rescue where you raise, it’s a disguised
if.
cherche(id) # appelé de très basraise NotFoundrescue NotFound
cherche(id) # appelé de très bas— Trois appels empilés :appelant,service,cherche.Three stacked calls:appelant,service,cherche.raise NotFound—raiseconstruit une stack trace et déroule la pile :serviceest sauté.raisebuilds a stack trace and unwinds the stack:serviceis skipped.rescue NotFound— Lerescuereprend la main loin de la cause. Justifié pour l'imprévu, coûteux pour l'attendu.Therescuetakes over far from the cause. Justified for the unexpected, wasteful for the expected.
La preuve, avec Ruby 3.4
h = {a: 1}
p h[:b] # => nil
p h.fetch(:b, 0) # => 0
h.fetch(:b) # KeyError
p Integer("12", exception: false) # => 12
p Integer("x", exception: false) # => nil
p [1, 2, 3].find { _1 > 5 } # => nilL’erreur, telle que Ruby l’écrit
h.fetch(:b)
key not found: :b (KeyError)Une valeur plutôt qu’une exception
def cherche(id) = id == 1 ? "Ada" : nil
p cherche(2)&.upcase # => nil
Result = Data.define(:ok, :valeur)
p Result.new(ok: false, valeur: "introuvable")Ce que l’image cache
Ce n’est pas une règle contre raise : une erreur de programmation, une ressource absente, un état impossible méritent une vraie exception, avec sa stack trace. La question est de savoir si l’appelant peut décider quoi faire sur place.
Pour aller plus loin
Le numéro ci-dessous détaille le choix entre lever et rendre une valeur, avec des exercices.
The proof, with Ruby 3.4
h = {a: 1}
p h[:b] # => nil
p h.fetch(:b, 0) # => 0
h.fetch(:b) # KeyError
p Integer("12", exception: false) # => 12
p Integer("x", exception: false) # => nil
p [1, 2, 3].find { _1 > 5 } # => nilThe error, as Ruby writes it
h.fetch(:b)
key not found: :b (KeyError)A value instead of an exception
def cherche(id) = id == 1 ? "Ada" : nil
p cherche(2)&.upcase # => nil
Result = Data.define(:ok, :valeur)
p Result.new(ok: false, valeur: "introuvable")What the picture hides
This is no rule against raise: a programming error, a missing resource, an impossible state deserve a real exception, with its stack trace. The question is whether the caller can decide what to do on the spot.
Go deeper
The issue below details the choice between raising and returning a value, with exercises.