Unchecked JavaScript exceptions can stop the current call stack before fallback logic, user messaging, or later work has a chance to run. A small try and catch block is useful around code that is expected to fail sometimes, such as parsing text from storage, an API response, or a form field.
The try block should stay close to the operation that may throw. The catch block receives the thrown value and can turn it into a log entry, returned object, fallback state, or user-facing message without spreading error checks through the rest of the function.
Malformed JSON is a good synchronous failure boundary because JSON.parse() throws SyntaxError before any parsed fields are available. Catching that expected error gives the caller one result shape for both valid and invalid input while unrelated errors can still be rethrown.
function loadSettings(jsonText) { try { const settings = JSON.parse(jsonText); return { ok: true, theme: settings.theme, retries: settings.retries, }; } catch (error) { if (!(error instanceof SyntaxError)) { throw error; } return { ok: false, error: `${error.name}: ${error.message}`, theme: "light", retries: 0, }; } } const validSettings = loadSettings('{"theme":"dark","retries":3}'); console.log(`valid theme: ${validSettings.theme}`); console.log(`valid retries: ${validSettings.retries}`); const brokenSettings = loadSettings("{'theme':'dark'}"); console.log(`caught error: ${brokenSettings.error}`); console.log(`fallback theme: ${brokenSettings.theme}`); console.log("application still running");
The function returns the same keys from both paths, so callers can check ok or use the fallback fields without wrapping every caller in its own try block.
try { const settings = JSON.parse(jsonText); return { ok: true, theme: settings.theme, retries: settings.retries, }; }
When JSON.parse() throws, the remaining statements inside try are skipped and control moves to catch.
} catch (error) { if (!(error instanceof SyntaxError)) { throw error; } return { ok: false, error: `${error.name}: ${error.message}`, theme: "light", retries: 0, }; }
The instanceof SyntaxError guard keeps malformed JSON in the fallback path while allowing unexpected failures to surface during development or monitoring.
$ node parse-settings.js valid theme: dark valid retries: 3 caught error: SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2) fallback theme: light application still running
The caught error line shows the SyntaxError name and message, the fallback theme line shows the returned default value, and the final line proves later code still ran.
$ rm parse-settings.js