You Can Throw Anything In JavaScript

Last updated 18th December, 2023

In JavaScript, you can throw anything. In a try block if you throw a value, that will be the value that the catch receives.

Say I wanted to throw a string message, and show that immediately to the user:

try {
  throw 'Something went wrong';
} catch (error) {
  console.log(error); // "Something went wrong"
}

You can throw an object literal in a throw statement:

try {
  throw {
    message: 'Something went wrong';
  };
} catch (error) {
  console.log(error.message); // "Something went wrong"
}

You can even throw symbols... if you really have the inclination:

try {
  throw Symbol(true);
} catch (error) {
  console.log(error); // "Symbol(true)"
}

I'm not saying that throwing anything other than an error is a good idea. But, it's cool to know you can.

No comments yet…

DevInTheWild.

Login To Add Comments.

Want More Like This?

Subscribe to occasional updates.

Related Articles

  • Registering routes is typically done statically in an index file, which can be pretty restrictive in complex applications. In this quick tutorial I'll show you a simple technique to get routes registering dynamically using Vue plugins