try / catch / finally
finally runs always
finally runs whether or not the try threw — even if the catch threw, even if a return happened. It's the only safe place for cleanup that MUST happen.
function withConnection(work) {
const conn = openConnection();
try {
return work(conn);
} catch (err) {
console.error("work failed:", err);
throw err;
} finally {
conn.close(); // ALWAYS runs
}
}Common shape
The "wrap a risky thing, always tear it down" pattern:
- Open a file → finally close it.
- Start a transaction → finally rollback if not committed.
- Show a spinner → finally hide it.
Re-throwing
throw err inside a catch re-throws the same error. The finally still runs first; then the throw propagates to the caller. The original stack is preserved.
return inside finally is a trap
return inside finally overrides any return from try/catch and silently swallows pending throws. Always use finally for SIDE EFFECTS, never for return values.
Inscris-toi pour coder
La théorie est ouverte à tous. L'éditeur, l'aperçu live et le check se débloquent avec un essai gratuit de 7 jours — carte requise, annulable à tout moment.
S'inscrire — essai gratuit →Les 10 premières leçons de chaque parcours sont gratuites. Pas de carte requise.