En bref. Trois articles ont répété « ne panique pas, propage » : Option, Result et ?, thiserror et anyhow. Celui-ci trace la limite. Une entrée extérieure qui échoue est un cas normal : Result. Une promesse interne qui cède est un bug : là, paniquer est correct. Le débordement d’entier montre les deux côtés. rustc refuse 255 + 1 dans un u8, le profil debug panique sur 200 + 60 (attempt to add with overflow), et le profil release affiche total = 4 sans rien dire.
Le modèle en une phrase
Un
Resultrépond à une question du monde extérieur : « et si ça échoue ? ». Unpanicsignale une promesse que le code s’était faite à lui-même, et qu’il vient de rompre.
Il y a donc une frontière. Ce qui la traverse depuis l’extérieur est vérifié, et son échec repart en Result. Ce qui vit à l’intérieur repose sur des invariants : si l’un d’eux tombe, personne en amont ne peut réparer, et s’arrêter net est la réponse honnête.
In short. Three articles repeated “don’t panic, propagate”: Option, Result and ?, thiserror and anyhow. This one draws the line. Outside input that fails is a normal case: Result. An internal promise that breaks is a bug: there, panicking is correct. Integer overflow shows both sides. rustc rejects 255 + 1 in a u8, the debug profile panics on 200 + 60 (attempt to add with overflow), and the release profile prints total = 4 without a word.
The model in one sentence
A
Resultanswers a question from the outside world: “what if it fails?”. Apanicflags a promise the code had made to itself, and has just broken.
So there is a boundary. What crosses it from outside is checked, and its failure goes back as a Result. What lives inside rests on invariants: if one falls, nobody upstream can repair it, and stopping dead is the honest answer.
fn lire_quantite(saisie: &str) -> Result<u8, ParseIntError> {saisie.trim().parse()}
- La saisie vient de l'extérieur : qu'elle soit fausse est un cas normal. Au portail,
parserenvoie unResult, et"douze"repart enErr. L'appelant décide.The input comes from outside: it being wrong is a normal case. At the gate,parsereturns aResult, and"douze"goes back asErr. The caller decides. - Le contre-exemple :
unwrap()sur l'entrée d'autrui. Une faute de frappe de l'utilisateur fait tomber le programme. Ce n'est pas un bug du code, c'est une erreur attendue traitée comme un bug.The counter-example:unwrap()on someone else's input. A user's typo brings the program down. It isn't a bug in the code, it's an expected error treated as a bug. - À l'intérieur, une promesse : un
Lotn'est jamais vide, parce queLot::newle vérifie une fois. Ensuite,expectparie sans risque, et son message dit pourquoi le pari tient.Inside, a promise: aLotis never empty, becauseLot::newchecks it once. After that,expectbets safely, and its message says why the bet holds. - Notre propre code fabrique un
Lotvide sans passer parnew. La promesse est rompue de l'intérieur : c'est un bug, et ici paniquer est correct. Le message d'expectdésigne la promesse qui a cédé.Our own code builds an emptyLotwithout going throughnew. The promise is broken from inside: it's a bug, and here panicking is correct. Theexpectmessage names the promise that gave way.
À la frontière : l’échec attendu
Une quantité tapée par un utilisateur sera fausse un jour. Ce n’est pas un bug, c’est la vie d’une saisie :
use std::num::ParseIntError;
fn lire_quantite(saisie: &str) -> Result<u8, ParseIntError> {
saisie.trim().parse()
}12 -> 12
douze -> refusé : invalid digit found in stringLe contre-exemple, c’est la même fonction avec unwrap() pour faire taire le compilateur :
fn lire_quantite(saisie: &str) -> u8 {
saisie.trim().parse().unwrap()
}thread 'main' (343911) panicked at lib_panique.rs:2:27:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceCode de sortie 101. Le nombre entre parenthèses est l’identifiant du thread, il change à chaque exécution. Une faute de frappe a arrêté le programme : c’est l’exception non gérée des autres langages, revenue par la petite porte. Dans une bibliothèque, c’est pire : l’appelant n’a aucun moyen de l’éviter, la signature ne dit même pas que ça peut échouer.
À l’intérieur : la promesse
Un invariant est une promesse que votre code se fait : « ce lot n’est jamais vide », « cet index a été vérifié ». On la vérifie une fois, au portail, puis on s’appuie dessus :
struct Lot { stocks: Vec<u8> }
impl Lot {
fn new(stocks: Vec<u8>) -> Option<Lot> {
if stocks.is_empty() { None } else { Some(Lot { stocks }) }
}
fn plus_grand(&self) -> u8 {
*self.stocks.iter().max().expect("Lot::new refuse un lot vide")
}
}max() renvoie un Option, parce qu’il ne sait rien de la promesse. plus_grand, lui, la connaît. Renvoyer un Option<u8> ici forcerait chaque appelant à traiter un cas qui ne peut pas arriver. Ce serait un mensonge dans la signature. expect parie, et son message dit pourquoi le pari tient.
Si le pari perd, c’est que notre propre code a fabriqué un Lot sans passer par new :
let bris = Lot { stocks: vec![] };
println!("{}", bris.plus_grand());thread 'main' (343844) panicked at frontiere.rs:16:35:
Lot::new refuse un lot videLe message désigne la promesse qui a cédé, pas seulement l’endroit. C’est pour ça qu’on préfère expect à unwrap : le texte est la première chose qu’on lira dans le log. Pour verrouiller la promesse, le champ stocks reste privé hors du module (voir newtype et type-state).
assert! sert au même usage, quand l’invariant n’est pas un Option à ouvrir :
fn moyenne(v: &[u32]) -> u32 {
assert!(!v.is_empty(), "moyenne() appelée sur une tranche vide");
v.iter().sum::<u32>() / v.len() as u32
}thread 'main' (343982) panicked at assert.rs:2:5:
moyenne() appelée sur une tranche videLe débordement : qui vérifie la promesse ?
Un u8 promet de tenir entre 0 et 255. Qui vérifie cette promesse dépend du moment où la valeur est connue.
À la compilation, si le calcul est constant :
let x: u8 = 255 + 1;error: this arithmetic operation will overflow
--> constant.rs:2:17
|
2 | let x: u8 = 255 + 1;
| ^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by defaultÀ l’exécution, si la valeur vient de l’extérieur, rustc ne voit plus rien :
fn total(stocks: &[u8]) -> u8 {
let mut t: u8 = 0;
for s in stocks {
t += s;
}
t
}
fn main() {
let n: u8 = env::args().nth(1).unwrap_or("200".into()).parse().expect("argument numérique");
let stocks = [n, 60];
println!("total = {}", total(&stocks));
}Compilé sans option (profil debug) :
thread 'main' (343433) panicked at somme.rs:6:9:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceCompilé avec -O (profil release) :
total = 4Code de sortie 0. En release, Rust retire la vérification par défaut et l’addition enroule : 260 modulo 256 vaut 4. Le bug n’a pas disparu, il est devenu silencieux. C’est le pire des deux mondes : un stock faux, sans alarme.
compilation debug release
255 + 1 erreur — —
200 + 60 rien à voir panic (101) 4, code 0
checked_add rien à voir None NoneLa sortie, c’est de dire quel débordement on veut :
fn total(stocks: &[u8]) -> Option<u8> {
stocks.iter().try_fold(0u8, |t, &s| t.checked_add(s))
}None // total(&[200, 60])
Some(160) // total(&[100, 60])
4 // 200u8.wrapping_add(60)
255 // 200u8.saturating_add(60)checked_add met le cas dans le type, et la frontière en fait un Result. wrapping_add dit « le tour de compteur est voulu » (un hachage, un compteur circulaire). saturating_add dit « on plafonne ». Dans tous les profils, le comportement est le même.
Ce que l’image cache
overflow-checksse règle.overflow-checks = truedans[profile.release]duCargo.tomlgarde la panique en release. Vérifié avec-O -C overflow-checks=on: attempt to add with overflow, code 101.debug_assert!disparaît en release. Le mêmedebug_assert!(!v.is_empty())panique en debug et laisse passer en release (le programme affichepassé, code 0). À réserver aux vérifications coûteuses, jamais à ce qui protège la mémoire ou les données.- Un panic se rattrape à une frontière, pas partout.
std::panic::catch_unwindpermet à un serveur de transformer une requête qui panique en réponse 500 et de continuer :requête 60 : 500, le serveur continue. Le message de panic s’affiche quand même. Avecpanic = "abort", rien ne se rattrape : le processus s’arrête, code 134. unwrap()partout n’est pas une stratégie. Chaqueunwrapest un pari. S’il porte sur l’entrée d’autrui, il perdra un jour. S’il porte sur une promesse interne, écrivez-la dans unexpect.
Pour aller plus loin
- Volume 4, numéro 03 de The Rust Loop, panic, unwrap et les invariants, qui compare six traces de panique réelles et trois cas de terrain : la découpe d’une chaîne, le débordement, la valeur par défaut qui ment (lien en bas de page).
- Articles précédents : le move (E0382), l’emprunt (E0502), les slices, les lifetimes (E0106), l’élision,
'static, enums et match (E0004), Option et unwrap, newtype et type-state (E0599), Result et?(E0277), thiserror et anyhow (E0119). - The Rust Book : To panic! or Not to panic!
- Documentation de
u8::checked_add - Cargo : les profils et
overflow-checks
At the boundary: the expected failure
A quantity typed by a user will be wrong one day. It isn’t a bug, it’s the life of an input:
use std::num::ParseIntError;
fn lire_quantite(saisie: &str) -> Result<u8, ParseIntError> {
saisie.trim().parse()
}12 -> 12
douze -> refusé : invalid digit found in stringThe counter-example is the same function with unwrap() to silence the compiler:
fn lire_quantite(saisie: &str) -> u8 {
saisie.trim().parse().unwrap()
}thread 'main' (343911) panicked at lib_panique.rs:2:27:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceExit code 101. The number in parentheses is the thread id, it changes on every run. A typo stopped the program: it’s other languages’ unhandled exception, back through the side door. In a library it’s worse: the caller has no way to avoid it, the signature doesn’t even say it can fail.
Inside: the promise
An invariant is a promise your code makes to itself: “this lot is never empty”, “this index has been checked”. You check it once, at the gate, then rely on it:
struct Lot { stocks: Vec<u8> }
impl Lot {
fn new(stocks: Vec<u8>) -> Option<Lot> {
if stocks.is_empty() { None } else { Some(Lot { stocks }) }
}
fn plus_grand(&self) -> u8 {
*self.stocks.iter().max().expect("Lot::new refuse un lot vide")
}
}max() returns an Option, because it knows nothing of the promise. plus_grand does. Returning an Option<u8> here would force every caller to handle a case that cannot happen. That would be a lie in the signature. expect bets, and its message says why the bet holds.
If the bet loses, our own code built a Lot without going through new:
let bris = Lot { stocks: vec![] };
println!("{}", bris.plus_grand());thread 'main' (343844) panicked at frontiere.rs:16:35:
Lot::new refuse un lot videThe message names the promise that gave way, not just the place. That’s why expect beats unwrap: the text is the first thing anyone reads in the log. To lock the promise, the stocks field stays private outside the module (see newtype and type-state).
assert! serves the same purpose when the invariant isn’t an Option to open:
fn moyenne(v: &[u32]) -> u32 {
assert!(!v.is_empty(), "moyenne() appelée sur une tranche vide");
v.iter().sum::<u32>() / v.len() as u32
}thread 'main' (343982) panicked at assert.rs:2:5:
moyenne() appelée sur une tranche videOverflow: who checks the promise?
A u8 promises to fit between 0 and 255. Who checks that promise depends on when the value is known.
At compile time, if the computation is constant:
let x: u8 = 255 + 1;error: this arithmetic operation will overflow
--> constant.rs:2:17
|
2 | let x: u8 = 255 + 1;
| ^^^^^^^ attempt to compute `u8::MAX + 1_u8`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by defaultAt runtime, if the value comes from outside, rustc can’t see anything any more:
fn total(stocks: &[u8]) -> u8 {
let mut t: u8 = 0;
for s in stocks {
t += s;
}
t
}
fn main() {
let n: u8 = env::args().nth(1).unwrap_or("200".into()).parse().expect("argument numérique");
let stocks = [n, 60];
println!("total = {}", total(&stocks));
}Built with no options (debug profile):
thread 'main' (343433) panicked at somme.rs:6:9:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceBuilt with -O (release profile):
total = 4Exit code 0. In release, Rust removes the check by default and the addition wraps: 260 modulo 256 is 4. The bug hasn’t gone, it has gone quiet. It’s the worst of both worlds: a wrong stock, no alarm.
compile time debug release
255 + 1 error — —
200 + 60 nothing to see panic (101) 4, exit 0
checked_add nothing to see None NoneThe way out is to say which overflow you want:
fn total(stocks: &[u8]) -> Option<u8> {
stocks.iter().try_fold(0u8, |t, &s| t.checked_add(s))
}None // total(&[200, 60])
Some(160) // total(&[100, 60])
4 // 200u8.wrapping_add(60)
255 // 200u8.saturating_add(60)checked_add puts the case in the type, and the boundary turns it into a Result. wrapping_add says “wrapping is intended” (a hash, a circular counter). saturating_add says “we cap it”. In every profile, the behaviour is the same.
What the picture hides
overflow-checksis configurable.overflow-checks = truein[profile.release]ofCargo.tomlkeeps the panic in release. Verified with-O -C overflow-checks=on: attempt to add with overflow, exit 101.debug_assert!disappears in release. The samedebug_assert!(!v.is_empty())panics in debug and lets it through in release (the program printspassé, exit 0). Keep it for expensive checks, never for what protects memory or data.- A panic can be caught at a boundary, not everywhere.
std::panic::catch_unwindlets a server turn a panicking request into a 500 response and carry on:requête 60 : 500, le serveur continue. The panic message is still printed. Withpanic = "abort", nothing can be caught: the process stops, exit code 134. unwrap()everywhere is not a strategy. Everyunwrapis a bet. If it’s on someone else’s input, it will lose one day. If it’s on an internal promise, write that promise in anexpect.
Going further
- Volume 4, issue 03 of The Rust Loop, panic, unwrap & invariants, which compares six real panic traces and three field cases: slicing a string, overflow, the default value that lies (link at the bottom of the page).
- Previous articles: move (E0382), borrowing (E0502), slices, lifetimes (E0106), elision,
'static, enums and match (E0004), Option and unwrap, newtype and type-state (E0599), Result and?(E0277), thiserror and anyhow (E0119). - The Rust Book: To panic! or Not to panic!
u8::checked_adddocumentation- Cargo: profiles and
overflow-checks