JavaScript try/catch: Recover from Expected Failures
Quick answer
Try executes a protected block and catch handles an exception thrown during that synchronous execution. It allows callers to choose an appropriate recovery path.
How it works
try { work(); } catch (error) { recover(error); } catches errors propagated through calls inside try. Catch has its own binding scope and optional binding syntax catch { ... }. Catch code can itself throw; the same catch does not catch its own new exception. Promise rejections need asynchronous handling, taught later.
function parseCount(n) { if (n < 0) throw new RangeError("count"); return n; }try { console.log(parseCount(-3)); } catch (e) { console.log(e.name); }console.log("done");Expected output in Node.js:
RangeErrordoneThe exception crosses the call and execution resumes after the handled try statement.
try { console.log("ready"); } catch { console.log("fallback"); }Expected output in Node.js:
readyCatch is skipped when the protected block completes normally.
Common mistakes
Do not silently swallow unexpected failures. Recover only when the fallback is correct, or propagate the exception.
Practice
Call a bounded validation function from try and select a documented fallback only for the expected failure.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript try/catch: Recover from Expected Failures — Knowledge Check
Apply the taught concept and predict the output.
When does a catch block execute?
Can a catch clause omit its error binding?
Does a synchronous try around scheduling a future callback automatically catch later callback errors?
What is the exact console output in JavaScript try/catch: Recover from Expected Failures example 1?
function parseCount(n) { if (n < 0) throw new RangeError("count"); return n; }try { console.log(parseCount(-3)); } catch (e) { console.log(e.name); }console.log("done");What is the exact console output in JavaScript try/catch: Recover from Expected Failures example 2?
try { console.log("ready"); } catch { console.log("fallback"); }