An exception interrupts the current JavaScript call path unless nearby code handles it or a caller catches it. A narrow try and catch boundary lets an expected failure return a controlled result while unexpected failures remain visible.
The try block belongs around the operation that can throw, not around an entire feature. When an exception occurs, execution skips the remaining statements in try and enters catch with the thrown value.
Malformed JSON provides a clear synchronous example because JSON.parse() throws SyntaxError for invalid grammar. The handler below returns a fallback only for that known error type and rethrows a TypeError or another unexpected exception for higher-level handling.
function readTheme(jsonText) { try { const settings = JSON.parse(jsonText); return { ok: true, theme: settings.theme, }; }
This first section is intentionally incomplete until the catch block is appended. Keeping only JSON.parse() and its dependent property read inside try prevents unrelated code from entering the same error boundary.
catch (error) { if (!(error instanceof SyntaxError)) { throw error; } return { ok: false, theme: "system", error: error.name, }; } }
The instanceof SyntaxError guard keeps malformed JSON in the fallback path while allowing unexpected failures to surface during development or monitoring.
const validResult = readTheme('{"theme":"dark"}'); const invalidResult = readTheme("{'theme':'dark'}"); console.log(`valid theme: ${validResult.theme}`); console.log(`invalid input handled: ${!invalidResult.ok}`); console.log(`fallback theme: ${invalidResult.theme}`); console.log(`caught error type: ${invalidResult.error}`); try { readTheme("null"); } catch (error) { console.log(`unexpected error rethrown: ${error.name}`); }
The value null is valid JSON, but reading settings.theme from it throws TypeError. That failure must pass through the inner handler rather than being mislabeled as malformed JSON.
$ node parse-settings.js valid theme: dark invalid input handled: true fallback theme: system caught error type: SyntaxError unexpected error rethrown: TypeError
The malformed input reaches the fallback result, while the final line proves that the selective handler did not hide an unrelated programming error.