JavaScript try...catch and Error Handling

JavaScript try...catch handles exceptions thrown while code in a try block is executing. Put only code you can meaningfully recover from or report inside try; the catch block receives the thrown value, usually an Error object.

Basic syntax:

try {
  riskyOperation();
} catch (error) {
  console.error(error.message);
}

Handling an exception prevents that exception from propagating further only if the catch block does not throw it again. It does not make every programming error safe to ignore.

Basic try...catch Example Top ↑

The original page intentionally referenced an undefined variable. In modern code, the exception can be displayed in the console or a controlled UI message.

try {
  console.log(mySum); // ReferenceError
} catch (error) {
  console.error("There was an error:", error.message);
}

console.log("Execution can continue here");

Using the JavaScript Error Object Top ↑

Built-in errors normally provide useful properties such as name and message. Development tools may also expose a stack trace.

try {
  JSON.parse("invalid JSON");
} catch (error) {
  console.log(error.name);
  console.log(error.message);
  console.error(error);
}

The old tutorial used browser detection to choose between Firefox and Internet Explorer-specific error properties. That is no longer appropriate; use the standard error object rather than branching on browser names.

Creating an Exception with throw Top ↑

throw stops normal execution and sends a value to the nearest applicable catch handler. Although JavaScript allows throwing almost any value, throwing an Error object is usually better because it carries a standard name, message, and stack information.

function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }

  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (error) {
  console.error(error.message);
}

This updates the original example that threw a plain string.

Common Built-In JavaScript Error Types Top ↑

  • Error: generic base error.
  • TypeError: an operation or value has an inappropriate type or use.
  • RangeError: a numeric value or parameter falls outside an allowed range.
  • ReferenceError: code references an identifier that cannot be resolved.
  • SyntaxError: parsing or syntax is invalid; it is also used by APIs such as JSON.parse() for invalid input syntax.
  • URIError: URI encoding/decoding functions encounter an invalid sequence.
  • AggregateError: represents multiple errors in APIs that aggregate failures.
function checkNumber(value) {
  if (typeof value !== "number") {
    throw new TypeError("Expected a number");
  }

  if (value < 0 || value > 100) {
    throw new RangeError("Number must be between 0 and 100");
  }

  return value;
}

try {
  checkNumber(150);
} catch (error) {
  console.error(`${error.name}: ${error.message}`);
}

Running Cleanup Code with finally Top ↑

The optional finally block runs after try/catch handling whether an exception occurred or not. It is useful for cleanup that must happen on both success and failure.

let resourceOpen = false;

try {
  resourceOpen = true;
  console.log("Using resource");
} catch (error) {
  console.error(error);
} finally {
  resourceOpen = false;
  console.log("Cleanup complete");
}
Be careful with return in finally: it can override a value returned or an exception thrown earlier. Avoid that pattern unless you have a very specific reason.

Optional catch Binding Top ↑

If you do not need the error value, modern JavaScript allows catch without a parameter.

try {
  JSON.parse(input);
} catch {
  console.log("Input is not valid JSON");
}

Handle Known Errors and Rethrow Unexpected Ones Top ↑

A catch block should not silently absorb every failure. Handle errors you understand and rethrow unexpected errors so they remain visible to higher-level code or monitoring.

try {
  processData();
} catch (error) {
  if (error instanceof RangeError) {
    console.warn("Value is outside the supported range");
  } else {
    throw error;
  }
}

What try...catch Can and Cannot Catch Top ↑

A try...catch catches exceptions thrown synchronously while execution is inside its try block. It does not reach forward into a later timer callback simply because the timer was scheduled from inside the try block.

try {
  setTimeout(() => {
    // An exception thrown here happens later, outside the outer try block.
    console.log("Timer callback");
  }, 0);
} catch (error) {
  console.error(error);
}

Put error handling inside the asynchronous callback where appropriate, or use Promise/async error handling.

Handling Promise Errors with async/await Top ↑

Inside an async function, an awaited rejected promise behaves like a thrown exception and can be handled with try...catch.

async function loadData() {
  try {
    const response = await fetch("/api/data");

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("Unable to load data:", error.message);
    throw error;
  }
}

Without await, handle Promise rejections with .catch() or return the promise to a caller that handles it.

Nested try...catch Blocks Top ↑

A nested catch can handle a local failure while an outer handler remains responsible for other errors.

try {
  try {
    JSON.parse("bad json");
  } catch (error) {
    console.warn("Local parse problem");
    throw error;
  }
} catch (error) {
  console.error("Outer handler:", error.message);
}

Using throw for Application Validation Top ↑

throw can enforce a function's contract when invalid input means the function cannot continue normally.

function checkAge(age) {
  if (!Number.isInteger(age)) {
    throw new TypeError("Age must be an integer");
  }

  if (age < 18) {
    throw new RangeError("You must be at least 18 years old");
  }

  return true;
}

For normal form feedback, validation results can also be returned without throwing. Use exceptions for exceptional failure paths rather than as a replacement for every branch.

Syntax Errors vs Runtime Exceptions Top ↑

If JavaScript cannot parse a script at all, the code may fail before the surrounding runtime flow can execute. However, APIs such as JSON.parse() can throw a SyntaxError at runtime and that exception can be caught normally.

try {
  JSON.parse('{"name": }');
} catch (error) {
  if (error instanceof SyntaxError) {
    console.log("JSON text has invalid syntax");
  }
}

Modern Browser Error Reporting Top ↑

The original page described old Firefox and Internet Explorer error-console behavior. Today, use the browser developer tools console and debugger rather than browser-name detection. For application-wide reporting, browsers also expose error and unhandled-rejection events, but those are not substitutes for handling recoverable errors close to where they occur.

Common try...catch Mistakes Top ↑

  • Wrapping very large blocks in try and then hiding every error.
  • Throwing plain strings when an Error object would provide better diagnostic information.
  • Using browser sniffing to decide how an error object works.
  • Expecting an outer synchronous try block to catch exceptions from a later timer callback.
  • Forgetting to handle rejected promises.
  • Logging sensitive application data in error messages.
  • Using exceptions for ordinary expected branches where a return value or condition would be clearer.

Continue with browser navigator information, alert dialogs, if...else, and functions.




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer