Technical skill practice
JavaScript try...catch: Catch Parsing Errors and Awaited Rejections
try...catch handles an exception that reaches its protected execution. Await a Promise inside that boundary if you want its rejection handled there. A timer or unawaited task that fails later is not covered merely because it was started inside a try block.
The task
Create one synchronous parse failure and one rejected async operation. Record the two catches and the finally block so their actual ordering can be checked.
Runnable Node 22 example
const assert = require('node:assert/strict');
(async () => {
const trace = [];
try { JSON.parse('{bad'); }
catch (error) { assert(error instanceof SyntaxError); trace.push('parse caught'); }
try {
await Promise.reject(new Error('not ready'));
} catch (error) {
assert.equal(error.message, 'not ready');
trace.push('rejection caught');
} finally { trace.push('cleanup'); }
assert.deepEqual(trace, ['parse caught', 'rejection caught', 'cleanup']);
console.log(trace.join(' | '));
})().catch(error => { console.error(error); process.exitCode = 1; });
Expected output and explanation
The JSON operation throws before it returns, so the first catch sees a SyntaxError. Await converts the rejected operation into an exception at the second protected boundary. Its catch checks the known failure and the finally block then records cleanup.
The outer handler makes an unexpected failure in this demonstration visible as a nonzero process result. It does not hide every error under a success message. In application code, distinguish failures you can handle from those you should pass to a higher-level handler.
Output from the example
parse caught | rejection caught | cleanup
Pitfall to check
A return or throw inside finally can replace an earlier result or error. Keep cleanup from accidentally masking the event you were trying to report. Likewise, do not leave a started Promise unhandled and assume an unrelated surrounding catch will receive it.
Questions, answered
Does finally run only when an error occurs?
No. It also runs after a normal completion of the protected block, which is why it can hold appropriate cleanup.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.