LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 24 of 25

Error Handling Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Error Handling · Study material

Every real program meets bad input, missing files, failed network calls and bugs. Error handling decides what happens next: recover, retry, show a helpful message, or fail loudly instead of silently corrupting data. JavaScript gives you throw, try/catch/finally, a family of built-in error types, custom error classes, error.cause for wrapping, and promise rejections for asynchronous code. Interviews test the tricky parts – what finally does to a return, why try cannot catch a rejection without await, how to write custom errors and when not to swallow them. After the guide, practise with 60 questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – all run on Node.js.

try, catch and finally

Code that might fail goes in try. When something throws, the rest of try is skipped and catch receives the error. finally runs afterwards in every case – success, error, or even a return – making it the place for cleanup.

function parseScore(text) {
  try {
    console.log("try: parsing", JSON.stringify(text));
    const data = JSON.parse(text);           // throws SyntaxError on bad JSON
    console.log("try: success");
    return data.score;
  } catch (error) {
    console.log("catch:", error.name);       // jumps here; the rest of try is skipped
    return 0;
  } finally {
    console.log("finally: always runs");     // success or failure
  }
}
console.log("result:", parseScore('{"score": 88}'));
console.log("result:", parseScore("{score: 88}"));

Output

try: parsing "{\"score\": 88}"
try: success
finally: always runs
result: 88
try: parsing "{score: 88}"
catch: SyntaxError
finally: always runs
result: 0

Built-in error types

All built-in errors inherit from Error and have name, message and (in practice) stack.

TypeTypical cause
TypeErrorcalling a non-function, reading a property of null/undefined, assigning to a const
ReferenceErroran undeclared variable, using let/const before declaration (TDZ)
SyntaxErrorinvalid code (before it runs) or invalid JSON passed to JSON.parse (at run time)
RangeErrorinvalid array length, toFixed(101), too much recursion
URIErrormalformed decodeURIComponent input
AggregateErrorseveral errors at once (Promise.any, your own validation)
const attempts = {
  "null.length": () => null.length,                 // TypeError: using a value the wrong way
  "notDefined + 1": () => notDefined + 1,           // ReferenceError: unknown variable
  "new Array(-1)": () => new Array(-1),             // RangeError: value out of range
  'JSON.parse("{")': () => JSON.parse("{"),         // SyntaxError: invalid text to parse
  'decodeURIComponent("%")': () => decodeURIComponent("%"),   // URIError
};
for (const [code, run] of Object.entries(attempts)) {
  try {
    run();
  } catch (e) {
    console.log(code.padEnd(24), "→", e.name, e instanceof Error);
  }
}

Output

null.length              → TypeError true
notDefined + 1           → ReferenceError true
new Array(-1)            → RangeError true
JSON.parse("{")          → SyntaxError true
decodeURIComponent("%")  → URIError true

throw and the call stack

throw stops the current function and unwinds through its callers until a catch is found; if none is found, the program reports an uncaught error. You can throw any value, but always throw Error objects – they carry a message and a stack trace.

// A throw leaves every function until a catch is found
function level3() { throw new Error("disk full"); }
function level2() { level3(); console.log("never printed"); }
function level1() {
  try {
    level2();
  } catch (e) {
    console.log("level1 caught:", e.message);
  }
  console.log("level1 continues");
}
level1();

Output

level1 caught: disk full
level1 continues

Custom error classes

Extend Error to give failures a meaningful type and extra data. Call super(message), set this.name, and handle errors by type with instanceof – re-throwing what you do not handle.

class ValidationError extends Error {
  constructor(field, message) {
    super(message);                 // sets this.message (and the stack)
    this.name = "ValidationError";  // shown in String(error) and stack traces
    this.field = field;             // extra data for the handler
  }
}

function register(user) {
  if (!user.email?.includes("@")) throw new ValidationError("email", "Enter a valid email");
  return `Welcome, ${user.name}!`;
}

for (const user of [{ name: "Asha", email: "asha@lf.com" }, { name: "Ravi", email: "ravi.lf.com" }]) {
  try {
    console.log(register(user));
  } catch (e) {
    if (e instanceof ValidationError) console.log(`${e.name} on "${e.field}": ${e.message}`);
    else throw e;                   // not ours: let it propagate
  }
}

Output

Welcome, Asha!
ValidationError on "email": Enter a valid email

Wrapping errors with cause

When a low-level error should be reported at a higher level, wrap it: new Error("message", { cause: err }) (ES2022). The original error stays available for logging and debugging.

function readConfig() {
  try {
    return JSON.parse("{ port: 8080 }");     // invalid JSON
  } catch (err) {
    throw new Error("Could not load config", { cause: err });   // wrap, keep the original
  }
}
try {
  readConfig();
} catch (e) {
  console.log(e.message);
  console.log("caused by:", e.cause.name);
}

Output

Could not load config
caused by: SyntaxError

Errors in asynchronous code

A rejected promise is the asynchronous form of a throw. Handle it with await inside try/catch or with .catch. A plain try/catch around code that only starts a promise cannot see its rejection.

const loadUser = async (id) => {
  if (id <= 0) throw new RangeError("id must be positive");
  return { id, name: "Asha" };
};

// await + try/catch
try {
  await loadUser(-1);
} catch (e) {
  console.log("await caught:", e.name);
}

// promise .catch
await loadUser(0).catch((e) => console.log(".catch caught:", e.name));

// a try/catch WITHOUT await does not see the rejection
try {
  loadUser(-5).catch(() => console.log("handled by the promise's own .catch"));
  console.log("try block finished first");
} catch {
  console.log("never runs");
}

Output

await caught: RangeError
.catch caught: RangeError
try block finished first
handled by the promise's own .catch

Common mistakes

  • Empty catch blocks – errors disappear and bugs surface far away.
  • Throwing strings – no stack trace and no type checks.
  • Custom errors without this.name – they print as plain "Error".
  • Checking instanceof Error before the specific types – the specific branches never run.
  • return or throw in finally – silently replaces the real result or error.
  • Cleanup in try instead of finally – skipped when something fails.
  • Wrapping without cause – the original error is lost.
  • try/catch around un-awaited promises or callbacks – it cannot catch them.

Key points to remember

  • throw Error objects; catch where you can actually handle the problem.
  • finally always runs – use it for cleanup, not for return.
  • Every built-in error extends Error; check types with instanceof or name.
  • Custom errors: extends Error, super(message), this.name, extra fields.
  • Wrap with { cause } to keep the original error.
  • Async: await inside try/catch, or .catch on the promise.
  • Re-throw errors you do not handle.

Frequently asked questions

Should I wrap every function in try/catch?

No. Catch where you can do something useful – show a message, retry, use a fallback – usually at boundaries such as request handlers and UI events. Elsewhere let errors propagate.

Can try/catch catch syntax errors?

Not in the same script – a SyntaxError in your code stops the whole script before it runs. Run-time SyntaxErrors from JSON.parse or new Function are catchable.

How do I catch errors nobody handled?

Browsers fire window "error" and "unhandledrejection" events; Node.js emits process "uncaughtException" and "unhandledRejection". Use them for logging, not for normal control flow.

Where can I learn more?

Read try...catch, Custom errors and async and await in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links