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.
Steps to handle JavaScript errors with try-catch:
- Create parse-settings.js with the JSON parsing success path inside try.
- parse-settings.js
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.
- Append a catch block that handles SyntaxError and rethrows every other error.
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.
- Append calls that exercise valid JSON, malformed JSON, and an unexpected TypeError.
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.
- Run the completed script with Node.js to verify both handled and rethrown errors.
$ 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.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.