What can you throw in JavaScript?
You can throw absolutely any value. The language does not check what you throw, so a string, a number, a plain object, or an Error object are all allowed, and the catch block receives exactly the value that you threw.
// Anything can be thrown.
try {
throw 'a plain string';
} catch (err) {
console.log(typeof err, err); // "string" "a plain string"
}
try {
throw { code: 404, message: 'Not found' };
} catch (err) {
console.log(err.code); // 404
}
// Error objects carry a stack.
try {
throw new TypeError('bad type');
} catch (err) {
console.log(err instanceof Error); // true
console.log(err.name); // "TypeError"
}That freedom is real, and it is also a trap. Because a thrown value might not be an Error, any code that catches an error has to check what it received before it reads the message. Code that assumes err.message always exists gives you a confusing failure when something throws a string, and that happens more often than you would like in older code bases.
There is a good reason to prefer Error objects even though the language does not require them. An Error carries a name that tells you the category of the failure, a stack that tells you where it came from, and a cause that lets you chain errors together. A thrown string carries none of that, so all the useful context has to be typed into the string by hand, which makes it harder to log and impossible for a program to inspect.
One more thing is worth knowing. Throwing inside a catch block is a normal thing to do, and it is how you add context to a low-level failure. Just be careful about throwing from a finally block, because that will replace whatever the try block was in the middle of doing.