JavaScript Exception Handling: try, catch, finally and throw

Things go wrong in every real program: a server returns 500, a JSON file is malformed, an element never appears. Exception handling decides what happens next: retry, report a clear message, clean up, or stop. For testers it matters twice, because a test fails by throwing an error. In this lesson you will learn how try, catch, finally and throw work, what is inside an error object, the built-in error types and their real messages, and the habits that make failures easy to diagnose.

Advertisement

📖 What You’ll Learn: errors and exceptions, try…catch, the error object (name, message, stack, cause), built-in error types with real messages, throw and why to throw Error objects, catching selectively and rethrowing, finally and cleanup, optional catch binding, wrapping errors with cause, errors in async code, unhandled errors, and how assertion failures work in tests.


💥 What Is an Exception?

Definition: an exception is an error that is thrown while the program runs. It stops the current code immediately and travels up the call stack until some code catches it. If nothing catches it, Node.js prints the error and exits (in a browser, it is reported in the console).

📄 uncaught.js

function parsePrice(text) {
  const value = Number(text);
  if (Number.isNaN(value)) {
    throw new Error(`Not a price: "${text}"`);
  }
  return value;
}

console.log(parsePrice("499"));
console.log(parsePrice("free"));      // throws: nothing below this line runs
console.log("never printed");

⌨️ Terminal

node uncaught.js

🖥️ Output

499
/home/you/js-course/uncaught.js:4
    throw new Error(`Not a price: "${text}"`);
    ^

Error: Not a price: "free"
    at parsePrice (/home/you/js-course/uncaught.js:4:11)
    at Object.<anonymous> (/home/you/js-course/uncaught.js:10:13)

Node.js v26.13.0

The output shows the error type and message, then the stack trace: the chain of function calls that led to the error, with file names and line numbers. Read it from the top.


🛡️ try…catch

Wrap code that might fail in try { ... }. If an error is thrown inside, JavaScript jumps straight to catch (error) { ... }, and the program continues after the block.

📄 try-catch.js

function parsePrice(text) {
  const value = Number(text);
  if (Number.isNaN(value)) throw new Error(`Not a price: "${text}"`);
  return value;
}

for (const input of ["499", "free", "12.5"]) {
  try {
    const price = parsePrice(input);
    console.log("parsed:", price);
  } catch (error) {
    console.log("skipped:", error.message);
  }
}
console.log("loop finished");

⌨️ Terminal

node try-catch.js

🖥️ Output

parsed: 499
skipped: Not a price: "free"
parsed: 12.5
loop finished
  • Code in try after the failing line is skipped.
  • catch runs only if something was thrown; otherwise it is skipped.
  • The error variable exists only inside the catch block.

⚠️ Watch out: try...catch only catches errors thrown while the code inside it runs. It cannot catch a SyntaxError in the same file (the file never starts) or an error thrown later by a callback, such as inside setTimeout.


🔍 The Error Object

Errors are objects. The most useful properties are:

PropertyContains
nameThe error type, such as "TypeError"
messageA human-readable description
stackThe name, message and call stack as text (non-standard but available in all engines)
causeThe original error that caused this one (ES2022)

📄 error-object.js

function loadUser() {
  const response = undefined;      // pretend the API returned nothing
  return response.data;            // TypeError
}

try {
  loadUser();
} catch (err) {
  console.log("name:   ", err.name);
  console.log("message:", err.message);
  console.log("is Error?", err instanceof Error, err instanceof TypeError);
  console.log("stack, first 2 lines:\n" + err.stack.split("\n").slice(0, 2).join("\n"));
}

⌨️ Terminal

node error-object.js

🖥️ Output

name:    TypeError
message: Cannot read properties of undefined (reading 'data')
is Error? true true
stack, first 2 lines:
TypeError: Cannot read properties of undefined (reading 'data')
    at loadUser (/home/you/js-course/error-object.js:3:19)

Advertisement

📚 Built-in Error Types

JavaScript throws different error types for different problems. Recognising them speeds up debugging:

📄 types.js

const cases = {
  ReferenceError: () => notDefinedVariable,
  TypeError: () => null.length,
  RangeError: () => new Array(-1),
  SyntaxError: () => JSON.parse("{bad json}"),
  URIError: () => decodeURIComponent("%"),
};

for (const [expected, fn] of Object.entries(cases)) {
  try {
    fn();
  } catch (e) {
    console.log(`${e.name.padEnd(15)} ${e.message}`);
  }
}

⌨️ Terminal

node types.js

🖥️ Output

ReferenceError  notDefinedVariable is not defined
TypeError       Cannot read properties of null (reading 'length')
RangeError      Invalid array length
SyntaxError     Expected property name or '}' in JSON at position 1 (line 1 column 2)
URIError        URI malformed
TypeUsually meansTypical fix
ReferenceErrorA name is not defined (typo, missing import, used before declaration)Check spelling, imports and declaration order
TypeErrorWrong kind of value: calling a non-function, reading a property of null/undefined, assigning to a constantCheck what the value really is; often a missing await or empty result
RangeErrorA number is out of range, or the call stack overflowedValidate numbers; fix recursion
SyntaxErrorInvalid code, or invalid JSON passed to JSON.parseFix the code or the data
URIErrorMalformed URI in encodeURI/decodeURIValidate the string
AggregateErrorSeveral errors at once (for example Promise.any)Inspect err.errors

🚀 throw: Raising Your Own Errors

throw stops the current function and raises an exception. You can throw any value, but always throw an Error (or a subclass): only Error objects carry a stack trace and work with instanceof and test frameworks.

📄 throw.js

function withdraw(balance, amount) {
  if (typeof amount !== "number") throw new TypeError(`amount must be a number, got ${typeof amount}`);
  if (amount <= 0) throw new RangeError(`amount must be positive, got ${amount}`);
  if (amount > balance) throw new Error(`Insufficient funds: balance ${balance}, requested ${amount}`);
  return balance - amount;
}

for (const amount of [200, "200", -5, 5000]) {
  try {
    console.log("new balance:", withdraw(1000, amount));
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
}

try {
  throw "something broke";          // a string: works, but no stack, no name
} catch (e) {
  console.log(typeof e, e.stack);
}

⌨️ Terminal

node throw.js

🖥️ Output

new balance: 800
TypeError: amount must be a number, got string
RangeError: amount must be positive, got -5
Error: Insufficient funds: balance 1000, requested 5000
string undefined

💡 Tip: Write error messages that answer “what was expected, what happened, and with which input”: Expected status 200 but got 503 for GET /api/orders is far more useful than Request failed.


🎯 Catch Selectively and Rethrow

A catch block receives every error, including bugs you did not expect. Handle only the errors you know how to handle, and rethrow the rest so they are not hidden:

📄 rethrow.js

function readConfig(text) {
  try {
    return JSON.parse(text);
  } catch (e) {
    if (e instanceof SyntaxError) {
      console.log("config is not valid JSON, using defaults");
      return { retries: 0 };
    }
    throw e;                          // anything else is a real bug: let it propagate
  }
}

console.log(readConfig('{"retries": 2}'));
console.log(readConfig("{retries: 2}"));

⌨️ Terminal

node rethrow.js

🖥️ Output

{ retries: 2 }
config is not valid JSON, using defaults
{ retries: 0 }

⚠️ Watch out: An empty catch {} that swallows every error is one of the worst bugs in test code: the test keeps going with bad data, or passes while the feature is broken. At minimum, log the error; usually, rethrow it.


🧹 finally: Always Clean Up

A finally block runs after try and catch, whether or not an error happened, and even if the code returns early. Use it for cleanup: closing files, connections or browsers, stopping timers, deleting test data.

📄 finally.js

function runStep(name, shouldFail) {
  console.log(`open connection for ${name}`);
  try {
    if (shouldFail) throw new Error(`${name} failed`);
    return `${name} ok`;
  } catch (e) {
    console.log("caught:", e.message);
    return `${name} handled`;
  } finally {
    console.log(`close connection for ${name}`);   // always runs
  }
}

console.log(runStep("login", false));
console.log(runStep("payment", true));

⌨️ Terminal

node finally.js

🖥️ Output

open connection for login
close connection for login
login ok
open connection for payment
caught: payment failed
close connection for payment
payment handled

try...finally without a catch is also valid: the cleanup runs and the error still propagates to the caller, which is exactly what a test helper usually wants.

📄 try-finally.js

function withTempFile(action) {
  console.log("create temp file");
  try {
    return action();
  } finally {
    console.log("delete temp file");
  }
}

try {
  withTempFile(() => { throw new Error("upload failed"); });
} catch (e) {
  console.log("caller sees:", e.message);
}

⌨️ Terminal

node try-finally.js

🖥️ Output

create temp file
delete temp file
caller sees: upload failed

If you do not need the error object, you can omit it: try { ... } catch { ... } (optional catch binding, ES2019).


Advertisement

🔗 Wrapping Errors with cause

When you catch a low-level error and throw a more meaningful one, attach the original as cause (ES2022). The new message explains the context; the cause keeps the technical detail:

📄 cause.js

function loadTestData(json, file) {
  try {
    return JSON.parse(json);
  } catch (e) {
    throw new Error(`Could not load test data from ${file}`, { cause: e });
  }
}

try {
  loadTestData("{users: []}", "users.json");
} catch (e) {
  console.log(e.message);
  console.log("caused by:", e.cause.name, "-", e.cause.message);
}

⌨️ Terminal

node cause.js

🖥️ Output

Could not load test data from users.json
caused by: SyntaxError - Expected property name or '}' in JSON at position 1 (line 1 column 2)

⏳ Errors in Asynchronous Code

With async/await, try...catch works across await just like synchronous code. But an error thrown inside a callback that runs later cannot be caught by a try that has already finished:

📄 async-errors.js

const fetchOrder = async (id) => {
  await new Promise((r) => setTimeout(r, 5));
  if (id < 0) throw new Error(`Order ${id} not found`);
  return { id };
};

async function main() {
  try {
    console.log(await fetchOrder(7));
    console.log(await fetchOrder(-1));
  } catch (e) {
    console.log("caught async error:", e.message);
  }

  try {
    setTimeout(() => {
      try {
        throw new Error("thrown later in a callback");
      } catch (e) {
        console.log("must be caught inside the callback:", e.message);
      }
    }, 0);
  } catch {
    console.log("never reached");
  }
}
main();

⌨️ Terminal

node async-errors.js

🖥️ Output

{ id: 7 }
caught async error: Order -1 not found
must be caught inside the callback: thrown later in a callback

⚠️ Watch out: Forgetting await is the most common async error bug: try { saveOrder(); } catch {} does not catch a rejection from an async saveOrder, because the promise rejects after the try has ended. Node.js then reports an unhandled promise rejection and exits. Module 10 covers promises in depth.


🧪 Tester Scenario: How a Test Fails

Assertions are just functions that throw when a check fails. A test runner calls each test inside try...catch: no error means passed, an error means failed, and the error’s message becomes the failure report. This is why a swallowed error makes a test pass wrongly.

📄 test-fail.js

const assert = require("node:assert/strict");

function runTest(name, fn) {
  try {
    fn();
    console.log(`✓ ${name}`);
  } catch (e) {
    console.log(`✗ ${name}\n    ${e.name}: ${e.message.split("\n").filter(Boolean).slice(0, 2).join(" ")}`);
  }
}

const response = { status: 503, body: { items: [] } };

runTest("status is 200", () => assert.equal(response.status, 200));
runTest("items is an array", () => assert.ok(Array.isArray(response.body.items)));
runTest("swallowed error hides the bug", () => {
  try {
    assert.equal(response.status, 200);
  } catch {
    // nothing here: the failure disappears
  }
});

⌨️ Terminal

node test-fail.js

🖥️ Output

✗ status is 200
    AssertionError: Expected values to be strictly equal: 503 !== 200
✓ items is an array
✓ swallowed error hides the bug

The third “test” passes even though the status is wrong, because its catch swallowed the assertion error. Never wrap assertions in try...catch unless you rethrow.


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write safeDivide(a, b) that throws a RangeError when b is 0. Call it for (10, 2) and (10, 0) and print the result or the error message.

Show answer

📄 practice1.js

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

🖥️ Output

5
RangeError: Division by zero

Q2. Parse each string in ['{"a":1}', "not json", '[1,2]'] with JSON.parse, printing the parsed value or invalid.

Show answer

📄 practice2.js

for (const text of ['{"a":1}', "not json", "[1,2]"]) {
  try {
    console.log(JSON.parse(text));
  } catch {
    console.log("invalid:", text);
  }
}

🖥️ Output

{ a: 1 }
invalid: not json
[ 1, 2 ]

Q3. Predict the order of the printed lines, then run it.

function f() {
  try {
    console.log("try");
    return "returned";
  } finally {
    console.log("finally");
  }
}
console.log(f());
Show answer

📄 practice3.js

function f() {
  try {
    console.log("try");
    return "returned";
  } finally {
    console.log("finally");
  }
}
console.log(f());

🖥️ Output

try
finally
returned

finally runs before the function actually returns, so “finally” is printed before the returned value is logged.

Q4. Write getAge(user) that throws a TypeError if user is not an object and an Error if age is missing. Test it with null, {} and { age: 30 }.

Show answer

📄 practice4.js

function getAge(user) {
  if (typeof user !== "object" || user === null) throw new TypeError("user must be an object");
  if (!("age" in user)) throw new Error("user.age is missing");
  return user.age;
}
for (const u of [null, {}, { age: 30 }]) {
  try { console.log(getAge(u)); } catch (e) { console.log(`${e.name}: ${e.message}`); }
}

🖥️ Output

TypeError: user must be an object
Error: user.age is missing
30

Q5. Wrap a failing JSON.parse in a new error "Bad API response" with the original error as cause, then print both messages.

Show answer

📄 practice5.js

try {
  try {
    JSON.parse("<html>502</html>");
  } catch (e) {
    throw new Error("Bad API response", { cause: e });
  }
} catch (e) {
  console.log(e.message, "|", e.cause.message);
}

🖥️ Output

Bad API response | Unexpected token '<', "<html>502</html>" is not valid JSON

Q6. Fix this helper so the error is not swallowed: it should log a message and then let the error reach the caller.

function clickSave(save) {
  try {
    save();
  } catch (e) {
  }
}
Show answer

📄 practice6.js

function clickSave(save) {
  try {
    save();
  } catch (e) {
    console.log("clickSave failed:", e.message);
    throw e;
  }
}
try {
  clickSave(() => { throw new Error("Save button disabled"); });
} catch (e) {
  console.log("caller sees:", e.message);
}

🖥️ Output

clickSave failed: Save button disabled
caller sees: Save button disabled

🧠 MCQ Quiz: Exception Handling

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What happens to the remaining code in a try block after an error is thrown?
  2. When does a finally block run?
  3. What does null.length throw?
  4. What does using an undeclared variable throw?
  5. What does JSON.parse("{bad}") throw?
  6. Why should you throw Error objects instead of strings?
  7. What is the purpose of throw e; inside catch?
  8. What does the cause option do?
  9. Can try/catch catch an error thrown later inside setTimeout’s callback?
  10. Why does a test pass when its assertion is wrapped in an empty catch?

💼 Interview Questions and Answers

Q1. Explain try, catch and finally.

try contains code that may throw. If something throws, control jumps to catch, which receives the error. finally runs afterwards in every case (success, caught error, or even a return inside try/catch) and is used for cleanup. You can use try...catch, try...finally or all three.

Q2. What is the difference between TypeError, ReferenceError and SyntaxError?

ReferenceError: a variable name cannot be found (typo, missing import, temporal dead zone). TypeError: an operation is used on the wrong kind of value, such as calling something that is not a function or reading a property of undefined. SyntaxError: the code (or JSON) cannot be parsed at all; for code it is raised before the file runs.

Q3. What does finally return if both try and finally have return statements?

📄 finally-return.js

function f() {
  try {
    return "from try";
  } finally {
    return "from finally";
  }
}
console.log(f());

⌨️ Terminal

node finally-return.js

🖥️ Output

from finally

The finally return wins and silently replaces the try’s value (or even a thrown error). That is why returning from finally is considered bad practice; ESLint’s no-unsafe-finally rule reports it.

Q4. How should errors be handled in test automation code?

  • Let assertion errors propagate so the test fails with a clear message; never swallow them.
  • Catch only expected, recoverable errors (for example a known flaky third-party call) and rethrow everything else.
  • Add context when rethrowing (new Error("Login failed for user X", { cause })).
  • Use finally or framework hooks for cleanup (delete test data, close resources).
  • Always await async calls inside try so rejections are caught.

Advertisement

❓ Frequently Asked Questions

🤔 Should I wrap all my code in try/catch?

No. Catch errors only where you can do something useful: recover, add context, or clean up. Elsewhere let them propagate so they are reported with a full stack trace.

🤔 What is the difference between an error and an exception?

In JavaScript the terms are used almost interchangeably: an Error object describes the problem, and throwing it creates an exception that unwinds the call stack.

🤔 Can catch handle only one error type?

JavaScript has no typed catch clauses. Catch everything, check with instanceof or error.name, handle the types you expect, and rethrow the rest.

🤔 How do I see the full stack trace?

Print error.stack, or let the error go uncaught so Node.js prints it. For async code, run Node.js with the default async stack traces and use await consistently.


🏁 Summary

  • Exceptions stop the current code and travel up the call stack until caught; uncaught errors stop the program.
  • try...catch handles errors; finally always runs and is used for cleanup.
  • Error objects have name, message, stack and optional cause; learn the built-in types.
  • Throw Error objects with clear messages; catch selectively and rethrow what you cannot handle.
  • Assertions fail tests by throwing, so never swallow errors in test code; await async calls inside try.

Next, continue with Lesson 44: Custom Errors. For extra practice, solve the JavaScript exception handling practice programs.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in