Learn JavaScript
❯ errors_modules.try_catch

try, catch & finally in JavaScript

$concept

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.

$how it works
1

try the risky region

JSON.parse, property access on maybes, validated operations — code that can fail goes inside.

2

catch receives anything

catch (e) gets whatever was thrown — Errors normally, anything legally; optional binding skips it when unneeded.

3

finally always runs

Cleanup (close, unlock, hide spinner) in finally executes on success, failure, and early return alike.

4

Async needs await-inside

try { await risky(); } — bare try around promise creation catches nothing future; the await must sit inside.

$example
try {
JSON.parse("not json");
} catch (e) {
console.log("caught:", e instanceof SyntaxError);
} finally {
console.log("done");
}
Output
caught: true
done
1JSON.parse throws SyntaxError on malformed input — the try region's risk realized.
2catch receives it; instanceof confirms the class — caught: true prints.
3finally runs regardless — done prints on the failure path exactly as it would on success.
$use cases
JSON.parse guards on every untrusted payload
Cleanup in finally (spinners, locks, temp state)
Awaited async operations inside try blocks
Optional catch binding for cleanup-only handling

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.