#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Error handling mechanisms

Error handling is how a JavaScript program deals with something going wrong while it runs, such as invalid input, a failed network request or a missing value, without crashing the whole page. The core tools are try, catch, finally and throw, plus their asynchronous equivalents for promises.

try, catch and finally

Code that might fail goes inside a try block. If any line throws an error, JavaScript skips the rest of that block and jumps to catch, passing the error object. The finally block runs afterwards in every case, whether an error happened or not, which makes it ideal for cleanup such as hiding a loading spinner.

function parseSettings(text) {
  try {
    const settings = JSON.parse(text);
    if (!settings.theme) {
      throw new Error("Missing theme setting");
    }
    return settings;
  } catch (error) {
    console.error(`${error.name}: ${error.message}`);
    return { theme: "light" };     // safe fallback
  } finally {
    console.log("Settings check finished");
  }
}

parseSettings('{"theme":"dark"}');  // returns { theme: "dark" }
parseSettings("not json");         // logs SyntaxError, returns fallback

Throwing your own errors

The throw statement lets your code signal a problem. You can throw anything, but always throw an Error object (or one of its subtypes), because it carries a message, a name and a stack trace that shows where it happened. Throwing a plain string loses the stack trace.

For larger programs you can create custom error types by extending Error:

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

try {
  throw new ValidationError("email", "Email is required");
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(`Fix the ${err.field} field`);
  } else {
    throw err;   // not ours: pass it on
  }
}

Built-in error types

  • SyntaxError: invalid code or invalid JSON passed to JSON.parse.
  • ReferenceError: using a variable that does not exist.
  • TypeError: using a value the wrong way, such as calling undefined as a function.
  • RangeError: a number outside the allowed range, such as an invalid array length.

Errors in asynchronous code

A try...catch only catches errors thrown while its block is running. A callback passed to setTimeout runs later, so an error thrown inside it escapes the surrounding try. Promises have their own path: use .catch() on the chain, or use async functions where await lets a normal try...catch handle rejected promises.

The swallowed error

The most damaging habit is an empty catch block, written just to make an error disappear. The program carries on with missing data, and the real problem shows up somewhere else much later, with no clue about the cause. At minimum, log the error. Better, catch only errors you know how to handle and re-throw the rest, as the ValidationError example does.

Also avoid wrapping huge chunks of code in a single try. Keep the block around the specific operation that can fail, so you know exactly what went wrong when you land in catch.

A last line of defence

Some errors will always slip through. Browsers fire a global error event on window for uncaught exceptions and an unhandledrejection event for promises nobody caught. Listening to them lets you log problems or show a friendly message instead of leaving the page in a broken state. Treat these listeners as a safety net for reporting, not as a replacement for handling errors close to where they happen.

When you show an error to a user, keep the wording human, such as "Could not load your orders, please try again", and keep technical details like stack traces in the console or your logs.

Takeaway: wrap risky operations in focused try blocks, throw real Error objects, clean up in finally, handle promise rejections separately, and never leave a catch empty.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course