try / catch / finally
Runs a block and, if it throws, catches the error instead of crashing the program; finally always runs afterward.
try { } catch (error) { } finally { }
Purpose
try runs a block of code; if anything inside it throws, catch runs instead of letting the error
crash the program (or propagate to the caller). finally, if present, always runs afterward โ
whether or not an error occurred, and even if try or catch returns early.
Syntax
function parseConfig(json) {
try {
return JSON.parse(json);
} catch (error) {
console.error('Invalid config JSON:', error.message);
return {};
} finally {
console.log('Parse attempt finished.');
}
}
Behavior notes
catch (error)receives the thrown value โ conventionally anErrorinstance, with.messageand.nameproperties, though technically any value can be thrown.catchcan be omitted if onlyfinallyis needed (try { } finally { }) โ useful for cleanup that must run whether or not an error occurred, without handling the error at that level.- Only synchronous errors thrown directly inside the
tryblock are caught. A callback scheduled from insidetry(asetTimeout, for instance) that throws later is not caught by thattryโ asynchronous error handling is covered later in this tier. - A
returninsidetryorcatchstill letsfinallyrun first before the function actually returns.
Common mistakes
- Wrapping too much code in one
tryblock, making it unclear which line could actually throw and obscuring what specifically is being guarded against. - Catching an error and silently doing nothing with it (
catch (e) {}) โ this hides real bugs. At minimum, log what was caught. - Expecting
try/catchto catch an error thrown inside an asynchronous callback scheduled from within thetryblock.
Runtime notes
Core ECMAScript statement, identical behavior in every browser and Node version.