Exceptions ou valeurs de retour : le modèle mental de quand ne pas lever en Ruby Exceptions or return values: the mental model of when not to raise in Ruby

Une exception déroule la pile et construit une stack trace : pour l'imprévu. Pour l'échec attendu, rends une valeur. Animation et sorties réelles de Ruby 3.4.An exception unwinds the stack and builds a stack trace: for the unexpected. For the expected failure, return a value. Animation and real Ruby 3.4 output.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ExceptionsExceptions
PubliéPublished

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 if dé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 bas
raise NotFound
rescue NotFound
Lever ou rendreRaise or returnappel en coursappel en coursappelantservicecherchehachuré rouge = levée ; gris = sauté par le déroulementred hatching = raised; grey = skipped by the unwindingvérifié avec Ruby 3.4checked with Ruby 3.4
  1. cherche(id) # appelé de très bas — Trois appels empilés : appelant, service, cherche.Three stacked calls: appelant, service, cherche.
  2. raise NotFound — raise construit une stack trace et déroule la pile : service est sauté.raise builds a stack trace and unwinds the stack: service is skipped.
  3. rescue NotFound — Le rescue reprend la main loin de la cause. Justifié pour l'imprévu, coûteux pour l'attendu.The rescue takes over far from the cause. Justified for the unexpected, wasteful for the expected.
Une exception déroule la pile et construit une stack trace : justifié pour l'imprévu. Pour un échec prévu, rends une valeur. Si tu rattrapes là où tu lèves, c'est un if déguisé.An exception unwinds the stack and builds a stack trace: justified for the unexpected. For an expected failure, return a value. If you rescue where you raise, it is a disguised if.

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 }         # => nil

L’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 }         # => nil

The 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.

Questions fréquentesFrequently asked questions

Quand lever une exception, quand rendre une valeur ?When should I raise, and when return a value?

Lève pour l'imprévu, ce que l'appelant ne peut pas gérer sur place. Pour une absence ou un échec attendu, rends une valeur : nil, un défaut, un objet résultat.Raise for the unexpected, what the caller can't handle on the spot. For an expected absence or failure, return a value: nil, a default, a result object.

Pourquoi une exception coûte-t-elle plus cher ?Why is an exception more expensive?

Elle construit une stack trace et déroule la pile. Sur 200 000 appels, Integer("x") rattrapé était environ six fois plus lent qu'avec exception: false.It builds a stack trace and unwinds the stack. Over 200,000 calls, a rescued Integer("x") was about six times slower than with exception: false.

Comment éviter de lever avec les méthodes standard ?How do I avoid raising with standard methods?

Avec fetch et un défaut (h.fetch(:b, 0)), Integer("x", exception: false), find qui rend nil. Chacune rend une valeur au lieu de lever.With fetch and a default (h.fetch(:b, 0)), Integer("x", exception: false), find returning nil. Each returns a value instead of raising.

Quel est le signe qu'une exception est mal placée ?What's the sign an exception is misplaced?

Si tu la rattrapes là où tu la lèves, c'est un if déguisé : une valeur de retour aurait fait le même travail, plus simplement.If you rescue it where you raise it, it's a disguised if: a return value would have done the same job, more simply.

À quoi sert un objet résultat ?What is a result object for?

À rendre succès ou échec sans lever, avec un message : Result.new(ok: false, valeur: "introuvable"). L'appelant teste ok au lieu de rattraper.To return success or failure without raising, with a message: Result.new(ok: false, valeur: "introuvable"). The caller tests ok instead of rescuing.

RubyExceptionsfetchValeur de retourModèle mental

← Tous les articlesAll articles