try, catch & finally in JavaScript
try marks code that might throw, catch receives the thrown value (any value, not just Errors — though throwing non-Errors is poor form), and finally runs regardless for cleanup. Optional catch binding (catch { without (e)) handles cleanup-only cases where the error itself is irrelevant.
Synchronous errors unwind to the nearest enclosing try; async rejections need await-inside-try or terminal .catch (a sync try cannot catch a future rejection). finally executes on every exit path — returns, throws, and completions alike.
try the risky region
JSON.parse, property access on maybes, validated operations — code that can fail goes inside.
catch receives anything
catch (e) gets whatever was thrown — Errors normally, anything legally; optional binding skips it when unneeded.
finally always runs
Cleanup (close, unlock, hide spinner) in finally executes on success, failure, and early return alike.
Async needs await-inside
try { await risky(); } — bare try around promise creation catches nothing future; the await must sit inside.
try { JSON.parse("not json");} catch (e) { console.log("caught:", e instanceof SyntaxError);} finally { console.log("done");}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.