LearnFrenzy
Sign in Take a free test

Error Handling and Debugging · Lesson 28 of 40

JavaScript try, catch, finally and Error Types

5 min read Updated Nov 7, 2026 Saurabh Samir

Things go wrong in every real program: the network drops, a user types letters into a phone field, an API changes its response. Good code expects failure, handles it where it can, and reports it clearly where it can't. JavaScript's tools for this are throw, try/catch/finally and the Error family of objects.

In this lesson

  • How try, catch and finally flow
  • Throwing errors, and why you should throw Error objects
  • The built-in error types
  • Rethrowing and wrapping errors with cause

try, catch, finally

function parseAge(input) {
  const age = Number(input);
  if (Number.isNaN(age)) throw new TypeError(`"${input}" is not a number`);
  if (age < 0 || age > 120) throw new RangeError(`Age ${age} is out of range`);
  return age;
}

for (const input of ["21", "abc", "200"]) {
  try {
    console.log("Valid age:", parseAge(input));
  } catch (err) {
    console.log(`${err.name}: ${err.message}`);
  } finally {
    console.log("-- checked", input);
  }
}

Output

Valid age: 21
-- checked 21
TypeError: "abc" is not a number
-- checked abc
RangeError: Age 200 is out of range
-- checked 200

How control flows

  1. try block runsline by line
  2. Error thrown?the rest of try is skipped; jump to catch(err)
  3. No errorcatch is skipped
  4. finally always runseven after return or an uncaught error – use it for cleanup

An error that no catch handles travels up the call stack. If nothing catches it, the browser logs it as "Uncaught" and the current task stops; a Node.js process exits.

Throw Error objects, not strings

function bad() { throw "Something broke"; }          // a string: no stack, no name
function good() { throw new Error("Something broke"); }

try { bad(); } catch (e) { console.log(typeof e, e.stack); }
try { good(); } catch (e) { console.log(typeof e, e.name, e.message, typeof e.stack); }

Output

string undefined
object Error Something broke string

An Error carries a name, a message and a stack trace showing where it was created – essential for debugging and for error-monitoring tools like Sentry.

Built-in error types

TypeThrown whenExample
TypeErrora value is the wrong type for the operationnull.length, calling a non-function
ReferenceErrora variable doesn't exist (or is in the TDZ)usrName typo
RangeErrora number is outside the allowed rangenew Array(-1), (1).toFixed(200)
SyntaxErrorinvalid code or invalid JSONJSON.parse("{bad}")
URIErrorbad URI encodingdecodeURIComponent("%")
AggregateErrorseveral errors at oncePromise.any when all fail
const attempts = [
  () => null.length,
  () => undefinedVariable,
  () => new Array(-1),
  () => JSON.parse("{bad}"),
  () => decodeURIComponent("%"),
];
for (const fn of attempts) {
  try { fn(); } catch (e) { console.log(e.constructor.name); }
}

Output

TypeError
ReferenceError
RangeError
SyntaxError
URIError

Catch only what you can handle

A catch that swallows every error hides real bugs. Handle the errors you expect and rethrow the rest:

function readSettings(json) {
  try {
    const s = JSON.parse(json);
    return s.theme.toUpperCase();
  } catch (err) {
    if (err instanceof SyntaxError) {
      return "LIGHT";                // expected: corrupt storage → use the default
    }
    throw err;                       // unexpected: let it surface
  }
}
console.log(readSettings('{"theme":"dark"}'));
console.log(readSettings("not json"));
try {
  readSettings("{}");                // s.theme is undefined – a real bug
} catch (err) {
  console.log("Bug surfaced:", err.name);
}

Output

DARK
LIGHT
Bug surfaced: TypeError

Wrapping errors with cause

When you catch a low-level error and throw a more meaningful one, keep the original as its cause so no information is lost:

function loadInvoice(id) {
  try {
    JSON.parse("{ broken");                 // pretend the file is corrupt
  } catch (err) {
    throw new Error(`Could not load invoice ${id}`, { cause: err });
  }
}
try {
  loadInvoice(1042);
} catch (err) {
  console.log(err.message);
  console.log("Caused by:", err.cause.name);
}

Output

Could not load invoice 1042
Caused by: SyntaxError

finally for cleanup

function withLoading(task) {
  console.log("spinner ON");
  try {
    return task();
  } finally {
    console.log("spinner OFF");      // runs even though try returned or threw
  }
}
console.log(withLoading(() => "done"));
try { withLoading(() => { throw new Error("failed"); }); } catch (e) { console.log(e.message); }

Output

spinner ON
spinner OFF
done
spinner ON
spinner OFF
failed

Common mistakes

  • Empty catch {} blocks that hide failures – at least log the error.
  • Using exceptions for normal control flow (like "user not found" in a search) – return a value instead.
  • Wrapping async calls in try/catch without await – the rejection happens later, outside the try.

Practice

Try it yourself

  1. Write safeDivide(a, b) that throws a RangeError for division by zero, and call it in a try/catch.

    Show solution
    function safeDivide(a, b) {
      if (b === 0) throw new RangeError("Cannot divide by zero");
      return a / b;
    }
    for (const [a, b] of [[10, 2], [5, 0]]) {
      try { console.log(safeDivide(a, b)); }
      catch (e) { console.log(`${e.name}: ${e.message}`); }
    }

    Output

    5
    RangeError: Cannot divide by zero

Quick check

Does finally run if try returns?

Yes – finally always runs.

Why throw new Error() instead of a string?

Error objects carry a name, message and stack trace.

What is error.cause for?

Keeping the original lower-level error when you throw a more descriptive one.

Summary

  • try runs code, catch handles thrown errors, finally always cleans up.
  • Throw Error objects; know TypeError, ReferenceError, RangeError and SyntaxError.
  • Catch what you can handle, rethrow the rest, and wrap with cause.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links