StandardError, jamais Exception : le modèle mental de l'arbre des erreurs en Ruby StandardError, never Exception: the mental model of the error tree in Ruby

Les exceptions Ruby forment un arbre : StandardError est le rattrapable, Exception contient aussi les signaux. Hérite de l'un, ne rattrape jamais l'autre. Ruby 3.4.Ruby exceptions form a tree: StandardError is the rescuable branch, Exception also holds signals. Inherit from one, never rescue the other. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
ExceptionsExceptions
PubliéPublished

En bref. Les exceptions Ruby forment un arbre, et une frontière commande tout : StandardError (le rattrapable, et tes erreurs) d’un côté, les signaux et la sortie du programme de l’autre.

Le modèle en une phrase

Hérite de StandardError, rattrape StandardError, jamais Exception : sinon tu avales le Ctrl-C.

In short. Ruby exceptions form a tree, and one boundary rules everything: StandardError (the rescuable branch, and your errors) on one side, signals and program exit on the other.

The model in one sentence

Inherit from StandardError, rescue StandardError, never Exception: otherwise you swallow Ctrl-C.

rescue # = rescue StandardError
raise PaiementRefuse
raise Interrupt # Ctrl-C
L'arbre des exceptionsThe exception treezone : StandardErrorzone : StandardErrorExceptionStandardErrorSignalExceptionSystemExitAppErrorArgumentErrorInterruptPaiementRefusefond pâle = zone du rescue ; trait épais = levéepale fill = rescue zone; thick outline = raisedvérifié avec Ruby 3.4checked with Ruby 3.4
  1. rescue # = rescue StandardError — Un rescue nu ne couvre que StandardError et ses descendants.A bare rescue only covers StandardError and its descendants.
  2. raise PaiementRefuse — Ton erreur hérite d'AppError < StandardError : elle tombe dans la zone.Your error inherits from AppError < StandardError: it falls inside the zone.
  3. raise Interrupt # Ctrl-C — Interrupt est hors zone : le Ctrl-C traverse le rescue et arrête le programme, comme il se doit.Interrupt is outside the zone: Ctrl-C passes through the rescue and stops the program, as it should.
Les exceptions forment un arbre. Hérite de StandardError, rattrape StandardError, jamais Exception : sinon on avale le Ctrl-C.Exceptions form a tree. Inherit from StandardError, rescue StandardError, never Exception: otherwise you swallow Ctrl-C.

La preuve, avec Ruby 3.4

class AppError < StandardError; end
class PaiementRefuse < AppError; end

p PaiementRefuse.ancestors.first(5)
# => [PaiementRefuse, AppError, StandardError, Exception, Object]

p Interrupt.superclass         # => SignalException
p SignalException.superclass   # => Exception

Le rescue nu laisse passer le Ctrl-C

begin
  begin; raise Interrupt; rescue => e; puts "rescue nu a pris"; end
rescue Exception => e
  puts "Interrupt a traversé le rescue nu : #{e.class}"
end

Le rescue nu n’a rien pris : seul le rescue Exception du dessus a vu passer Interrupt.

Rattraper large ou précis

begin
  raise PaiementRefuse, "carte"
rescue AppError => e
  puts "#{e.class} : #{e.message}"   # => PaiementRefuse : carte
end

Ce que l’image cache

La frontière protège, mais ne dispense pas de choisir la bonne classe : un rescue StandardError trop large peut encore cacher un bug. Rattrape ce que tu sais traiter, laisse monter le reste.

Pour aller plus loin

Le numéro ci-dessous détaille la hiérarchie des exceptions et le piège du rescue fourre-tout, avec des exercices.

The proof, with Ruby 3.4

class AppError < StandardError; end
class PaiementRefuse < AppError; end

p PaiementRefuse.ancestors.first(5)
# => [PaiementRefuse, AppError, StandardError, Exception, Object]

p Interrupt.superclass         # => SignalException
p SignalException.superclass   # => Exception

A bare rescue lets Ctrl-C through

begin
  begin; raise Interrupt; rescue => e; puts "rescue nu a pris"; end
rescue Exception => e
  puts "Interrupt a traversé le rescue nu : #{e.class}"
end

The bare rescue caught nothing: only the outer rescue Exception saw Interrupt go by.

Rescuing broadly or precisely

begin
  raise PaiementRefuse, "carte"
rescue AppError => e
  puts "#{e.class} : #{e.message}"   # => PaiementRefuse : carte
end

What the picture hides

The boundary protects you, but doesn’t excuse choosing the right class: an overly broad rescue StandardError can still hide a bug. Rescue what you know how to handle, let the rest bubble up.

Go deeper

The issue below details the exception hierarchy and the catch-all rescue trap, with exercises.

Questions fréquentesFrequently asked questions

De quelle classe hériter pour ses propres erreurs ?Which class should my own errors inherit from?

De StandardError, directement ou via une classe d'application (class AppError < StandardError). Elles sont ainsi rattrapables par un rescue ordinaire.From StandardError, directly or via an application class (class AppError < StandardError). They're then rescuable by an ordinary rescue.

Qu'attrape un rescue sans classe ?What does a rescue without a class catch?

StandardError et ses descendants. ArgumentError, TypeError, ZeroDivisionError en font partie ; Interrupt et SystemExit, non.StandardError and its descendants. ArgumentError, TypeError, ZeroDivisionError belong to it; Interrupt and SystemExit don't.

Pourquoi ne pas écrire rescue Exception ?Why not write rescue Exception?

Parce qu'il avale aussi Interrupt (Ctrl-C), SystemExit et NoMemoryError : le programme ne peut plus s'arrêter proprement.Because it also swallows Interrupt (Ctrl-C), SystemExit and NoMemoryError: the program can no longer stop cleanly.

Un rescue sur AppError attrape-t-il ses sous-classes ?Does rescuing AppError catch its subclasses?

Oui. rescue AppError attrape aussi PaiementRefuse, sous-classe d'AppError : on peut rattraper large ou précis selon la classe choisie.Yes. rescue AppError also catches PaiementRefuse, a subclass of AppError: you can rescue broadly or precisely depending on the class.

Que penser du rescue qui renvoie nil ?What about a rescue that returns nil?

À bannir : il transforme une erreur en valeur muette et le bug réapparaît plus loin. Mieux vaut rattraper une classe précise et agir.Avoid it: it turns an error into a mute value and the bug resurfaces elsewhere. Better to rescue a precise class and act.

RubyStandardErrorExceptionHiérarchieModèle mental

← Tous les articlesAll articles