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 an Error instance, with .message and .name properties, though technically any value can be thrown.
  • catch can be omitted if only finally is 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 try block are caught. A callback scheduled from inside try (a setTimeout, for instance) that throws later is not caught by that try โ€” asynchronous error handling is covered later in this tier.
  • A return inside try or catch still lets finally run first before the function actually returns.

Common mistakes

  • Wrapping too much code in one try block, 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/catch to catch an error thrown inside an asynchronous callback scheduled from within the try block.

Runtime notes

Core ECMAScript statement, identical behavior in every browser and Node version.

Taught in these lessons

Related reference