Lesson

JS Errors

10 min reading
Free Course

JavaScript Errors: try...catch...finally and Custom Errors

JavaScript errors signal runtime failures such as invalid JSON, failed network calls, or missing arguments. Wrapping risky operations in try...catch prevents your whole script from crashing and lets you show helpful recovery messages.

Built-In Error Types and finally

Every standard error inherits from Error and exposes .name, .message, and .stack:

  • SyntaxError: Invalid code syntax or malformed JSON.parse() input.
  • TypeError: Calling a non-function or reading properties on null/undefined.
  • ReferenceError: Reading an undeclared variable or accessing a let variable inside its Temporal Dead Zone.
  • RangeError: Numbers outside allowed limits, such as new Array(-1).

The optional finally block always executes whether try succeeded or threw, making it ideal for closing loading spinners or releasing file handles.

Throwing Meaningful Errors and Custom Subclasses

Throw new Error("...")—never plain strings—so you preserve full stack traces. Modern ES2022 also accepts { cause: err } to wrap low-level errors without losing the original failure.

class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function parseUserJson(raw) {
  try {
    const data = JSON.parse(raw);
    if (!data.email) {
      throw new ValidationError("Email field is required", "email");
    }
    return data;
  } catch (err) {
    console.error(`[${err.name}]`, err.message);
    return null;
  } finally {
    console.log("Parse attempt finished.");
  }
}

parseUserJson('{"name": "Ada"}');
parseUserJson("{broken-json");

Common Mistakes to Avoid

  • Empty catch (err) {} blocks: Swallowing errors silently hides bugs and makes production issues impossible to trace. Always log or handle the failure.
  • Throwing strings like throw "Failed": Plain strings lack .stack traces and break code expecting err.message. Always throw new Error(...).
  • Trying to catch async callback errors outside try...catch: A synchronous try { setTimeout(() => { throw ... }) } catch will not catch errors inside the later timer callback; handle errors inside the async function or .catch().

Frequently Asked Questions

Does finally still run if try or catch has a return statement?

Yes, finally always runs right before the function actually returns control to the caller.

How do I preserve the original error when rethrowing?

Pass it via ES2022 error cause: throw new Error("Failed to save user", { cause: originalError });.

Should I wrap every single line of code in try...catch?

No, wrap only boundaries where external failures happen—such as JSON.parse(), fetch(), localStorage reads, or third-party integrations.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum