Skip to main content

JavaScript Errors

JavaScript throw

Written by Published

throw raises an error deliberately when something is wrong.

You are not limited to the errors the language produces.

Throwing your own makes a function refuse bad input loudly.

Example

Example

javascript

function setAge(age) {
  if (age < 0) {
    throw new Error("age cannot be negative");
  }
  return age;
}

let message;
try {
  setAge(-5);
} catch (error) {
  message = error.message;
}

console.log(message);

The output is age cannot be negative.

Throwing Properly

throw stops the function immediately.

Always throw an Error object, not a plain string.

An Error carries a name, a message and a stack trace.

Syntax

Syntax

javascript

throw new Error("what went wrong");

Anything can be thrown, but only Error is useful.

It Stops the Function

Nothing after the throw runs.

Example

Example

javascript

function check(value) {
  const steps = [];
  steps.push("checking");
  if (!value) {
    throw new Error("no value given");
  }
  steps.push("never reached");
  return steps;
}

let message;
try {
  check(null);
} catch (error) {
  message = error.message;
}

console.log(message);

throw works like a return that signals failure.

Throw an Error, Not a String

A thrown string has no name, message or stack.

It also breaks any code expecting a proper error.

Example

Example

javascript

let details;

try {
  throw "just a string";
} catch (error) {
  details = typeof error + " with message " + (error.message === undefined ? "none" : error.message);
}

console.log(details);

The output shows a string with no message property.

Validating Input

Throwing makes it impossible for the caller to ignore the problem.

Example

Example

javascript

function divide(a, b) {
  if (b === 0) {
    throw new Error("cannot divide by zero");
  }
  return a / b;
}

console.log(divide(10, 2));

let message;
try {
  divide(10, 0);
} catch (error) {
  message = error.message;
}

console.log(message);

Returning null instead would be easy to overlook.

Throwing or Returning

Throw when the caller has made a mistake they must fix.

Return a value when failure is a normal, expected outcome.

Example

Example

javascript

function findUser(users, id) {
  const found = users.find(function (u) {
    return u.id === id;
  });
  return found === undefined ? null : found;
}

console.log(findUser([{ id: 1 }], 99));

Not finding a user is normal, so returning null is right.

Rethrowing

Catch, do something useful, then throw it onwards.

Example

Example

javascript

function load() {
  try {
    null.length;
  } catch (error) {
    throw new Error("loading failed: " + error.name);
  }
}

let message;
try {
  load();
} catch (error) {
  message = error.message;
}

console.log(message);

The new error adds context without losing the original cause.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript throw</title>
</head>
<body>

  <h1>throw</h1>

  <p id="out"></p>

  <script>
    function setAge(age) {
      if (typeof age !== "number") {
        throw new Error("age must be a number");
      }
      if (age < 0) {
        throw new Error("age cannot be negative");
      }
      return age;
    }

    const out = document.getElementById("out");

    try {
      out.textContent = "Age set to " + setAge(-5);
    } catch (error) {
      out.textContent = "Rejected: " + error.message;
    }
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a valid age:

Change -5 to 30 and see it accepted.

Important Points

  • throw raises an error deliberately.
  • It stops the function immediately.
  • Always throw an Error object.
  • Throw for mistakes the caller must fix.
  • Return a value when failure is expected.

Conclusion

Throwing turns a silent wrong answer into a loud, findable failure.

Validating input at the top of a function prevents a lot of confusion later.

The choice between throwing and returning is about whose mistake it is.