Thuta Learning
JavaScript
IntermediateProgrammingBeginner

Try...Catch

JavaScriptLesson 2025 min

What you'll walk away with

  • Predict the order in which try, catch and finally blocks run
  • Throw an error for invalid input with throw new Error(...)
  • Tell what try...catch can and cannot catch (setTimeout, Promises that are not awaited)
  • Choose between recovering with a fallback and rethrowing with added context

Explain it simply

Explain it simply

Picture a tightrope walker with a safety net underneath. If they never fall, the net is never used; if they do fall, the net catches them and the show goes on. And when the show ends, the rope gets packed away whether anyone fell or not.

The try block is the walk along the rope, the catch block is the net, and the finally block is the packing up that happens after every show. If an error is thrown inside try, the rest of try is skipped, control jumps straight to catch, and the program keeps running instead of crashing.

Problem → Why → Solution

The problem: an empty catch hides the error and the crash happens elsewhere

loadSettings() below swallows the error when JSON parsing fails and does nothing about it. The day a trailing comma slips into the settings file, the function returns undefined and the program carries on. The crash only happens later, where settings.theme is read, and its message seems to have nothing to do with JSON, which makes it painful to debug.

settings.js
function loadSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    // ignore it
  }
}

const settings = loadSettings('{"theme": "dark",}'); // trailing comma
console.log(settings.theme);
// TypeError: Cannot read properties of undefined (reading 'theme')

Why does this happen?

As soon as a catch block catches an error, the program assumes the problem has been handled. This catch fixes nothing; it lets execution continue with invalid state, undefined. Every catch must decide either to genuinely recover with a sensible fallback value or to add context and rethrow.

Core concept: how control flows through try, catch and finally

Code inside try runs normally. The moment a statement throws, the remaining lines of try are skipped and control jumps into the catch (error) block, where error holds an Error object with name, message and stack. If nothing throws, catch is skipped entirely. When you do not need the error object, you may write catch { ... } without a parameter.

finally always runs: whether try succeeded, whether catch ran, even when try contains a return. Use it for cleanup such as closing a file, hiding a loading spinner or releasing a lock. A return value from try is computed first, then finally runs, and only then is the value handed back to the caller. That is why the example prints "Division operation completed" before "Result: 5".

You can raise an error yourself with the throw statement: throw new Error("Cannot divide by zero"). In JavaScript 10 / 0 is not an error but Infinity, so business rules have to be checked and thrown by hand. try...catch catches synchronous errors and the rejections of Promises you await inside an async function. It cannot catch an error inside a setTimeout callback, a rejection from a Promise you did not await, or a syntax error in code that is still being parsed, because those happen after the try block has finished or before anything runs.

Once inside catch, answer one question: "can this code really resolve this error here?" If there is a meaningful fallback, such as showing cached data or using a default setting, recover. If not, add context and rethrow so that higher-level code, such as the page's error handler, makes the decision. Catching an error at the level that can actually deal with it beats grabbing it at the lowest level possible.

Mental model: a jump, a net and a cleanup
  1. Run try line by line
  2. A throw jumps straight to catch
  3. catch: recover or rethrow
  4. finally runs no matter what

catch is not where errors disappear; it is where you decide what to do about them.

General pattern

javascript
try {
  riskyOperation();              // may throw
} catch (error) {
  if (canRecover(error)) useFallback();
  else throw new Error("Context about the task", { cause: error });
} finally {
  cleanUp();                     // always runs
}

if (badInput) throw new Error("Describe what is wrong");

Inside catch, recoverable errors get a fallback; anything else is rethrown as a new error with context, linked to the original through { cause }. finally holds the cleanup.

Example: catching, throwing and finally

Predict the output before you run it, then check three details. Dividing by zero is not an error in JavaScript, so Infinity is printed before the ReferenceError is caught. "Division operation completed" appears before "Result: 5", because finally runs before the returned value reaches the console.log that called the function. And divideNumbers(10, 0) returns null, which is printed as "Result: null".

try-catch.js
// 1. Not every bad operation throws
try {
  const result = 10 / 0;
  console.log(result); // Infinity: not an error in JavaScript

  const x = y + 5; // ReferenceError: y is not defined
  console.log(x);  // never runs
} catch (error) {
  console.log(`Error caught: ${error.message}`);
}

// 2. throw, catch and finally together
function divideNumbers(a, b) {
  try {
    if (b === 0) {
      throw new Error("Cannot divide by zero");
    }
    return a / b;
  } catch (error) {
    console.log(`Error: ${error.message}`);
    return null;
  } finally {
    console.log("Division operation completed");
  }
}

console.log(`Result: ${divideNumbers(10, 2)}`);
console.log(`Result: ${divideNumbers(10, 0)}`);

// 3. Reacting to a specific kind of error
try {
  JSON.parse("invalid json");
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log("Invalid JSON format");
  }
}

Code breakdown

  1. Line 3const result = 10 / 0;

    Dividing by zero is not an error in JavaScript; it yields Infinity and never reaches catch. Rules like this have to be checked and thrown by you.

  2. Line 6const x = y + 5; // ReferenceError: y is not defined

    Reading the undeclared y throws a ReferenceError. The following console.log(x) is skipped and control lands in catch, printing "Error caught: y is not defined".

  3. Line 16throw new Error("Cannot divide by zero");

    When b is 0, the function throws its own Error object. return a / b is skipped, and catch prints the message and returns null.

  4. Lines 22-24} finally {

    finally runs for both calls. It runs before the return value reaches the caller, so "Division operation completed" appears before each "Result: ..." line.

  5. Line 34if (error instanceof SyntaxError) {

    instanceof checks the kind of error so the code reacts only to the kind it knows how to handle. That is sturdier than matching on the message text.

You should see
Infinity
Error caught: y is not defined
Division operation completed
Result: 5
Error: Cannot divide by zero
Division operation completed
Result: null
Invalid JSON format

async/await and error causes

Inside an async function, a rejected Promise that you await lands in catch just like a synchronous throw. When you rethrow, linking the original with new Error(message, { cause: error }) keeps both the "what were we doing" (loading the profile page) and the "why" (user not found) in your logs.

async-cause.js
async function fetchUser(id) {
  throw new Error(`User ${id} not found`);
}

async function loadProfile() {
  try {
    await fetchUser(7);
  } catch (error) {
    const wrapped = new Error("Could not load profile page", { cause: error });
    console.log(wrapped.message);              // Could not load profile page
    console.log(`Caused by: ${wrapped.cause.message}`); // Caused by: User 7 not found
  }
}

loadProfile();

In real projects

Where this shows up in real projects

In web apps, try...catch lives mostly at the system's boundaries: parsing JSON a user sent, fetching from an API, reading a file. A config loader, for instance, should say "fix the file" for malformed JSON and "the port field is required" for a missing field, as two distinct messages. The caller gets a consistent shape such as { ok, value, error } and checks it with a single if.

finally is the standard way to switch off a loading state in a UI: call setLoading(true), load data in try, and call setLoading(false) in finally, so a failed request never leaves the spinner turning forever. When logging errors on a server, record the error type, its cause and the operation in progress, but never put sensitive data such as passwords or tokens into the log.

Common mistakes

Common mistakes

1. Wrapping a huge block and treating every error the same

Put fifty lines in one try with a catch that says "Invalid input", and a TypeError caused by a typo in your own code gets reported as the user's fault. Keep try tight around the line that can legitimately fail, such as JSON.parse, and rethrow error types you did not expect.

2. Expecting try to catch errors from setTimeout or un-awaited Promises

In try { setTimeout(() => { throw new Error("late"); }, 0); } catch {}, the callback runs after the try block has finished, so the error is uncaught. Writing try { fetchUser(7); } without await leaves the rejection unhandled too. Put a try inside the callback itself, and await Promises.

3. Returning from inside finally

finally { return "done"; } overrides the value returned from try and even swallows an error rethrown from catch. Because an error can vanish completely this way, use finally only for cleanup and keep return and throw out of it.

Best practices

Best practices

  • Keep each try block tight around the operation that can fail.
  • Throw Error objects, never plain strings, so you get a name, a message and a stack.
  • When rethrowing, link the original error with { cause: error }.
  • Show users a simple message and keep details such as stack traces in the logs only.

Mini challenge

Mini challenge: a config parser

Write parseConfig() so it parses config text and tells malformed JSON apart from a missing field. The caller must always receive the same kind of result object.

  • Return { ok: true, value } on success
  • Return { ok: false, error: "Malformed JSON" } for invalid JSON
  • Return { ok: false, error: "Missing field: port" } when port is not a number
  • Rethrow any error that is not a SyntaxError
  • Count how many inputs were processed using finally
parse-config.js
let processed = 0;

function parseConfig(text) {
  try {
    // TODO: parse the text
    // TODO: return a "Missing field: port" result when port is not a number
    // TODO: return the success result
  } catch (error) {
    // TODO: rethrow anything that is not a SyntaxError
    // TODO: return the "Malformed JSON" result
  } finally {
    // TODO: count this input
  }
}

const inputs = ['{"port": 8080}', '{"port": 8080,}', '{"host": "localhost"}'];
// TODO: print "OK: port <n>" or "Failed: <error>" for each input,
// then "Processed <n> inputs"

Expected: The console prints four lines: OK: port 8080 Failed: Malformed JSON Failed: Missing field: port Processed 3 inputs

Show hint

JSON.parse throws a SyntaxError for invalid JSON. In catch, write if (!(error instanceof SyntaxError)) throw error; and handle only what remains. Remember that finally still runs when try returns.

Show solution
parse-config.js
let processed = 0;

function parseConfig(text) {
  try {
    const data = JSON.parse(text);
    if (typeof data.port !== "number") {
      return { ok: false, error: "Missing field: port" };
    }
    return { ok: true, value: data };
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error; // not ours to handle
    return { ok: false, error: "Malformed JSON" };
  } finally {
    processed += 1;
  }
}

const inputs = ['{"port": 8080}', '{"port": 8080,}', '{"host": "localhost"}'];
for (const text of inputs) {
  const result = parseConfig(text);
  console.log(result.ok ? `OK: port ${result.value.port}` : `Failed: ${result.error}`);
}
console.log(`Processed ${processed} inputs`);

Quick quiz 1 / 3

What does function f() { try { return "try"; } finally { console.log("finally"); } } console.log(f()); print?

Quick quiz 2 / 3

What happens with try { setTimeout(() => { throw new Error("late"); }, 0); } catch (e) { console.log("caught"); }?

Quick quiz 3 / 3

loadInvoice() hits a database error and its caller needs to know what failed. Which catch block is best?

What to remember

  • When try throws, the rest of it is skipped, catch runs and the program continues.
  • finally always runs, even after return or an error; use it for cleanup and keep return and throw out of it.
  • Business-rule violations must be thrown yourself with throw new Error(...); 10 / 0 is not an error.
  • try...catch sees synchronous errors and awaited rejections only; every catch should recover or rethrow.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Try...Catch | Thuta Learning