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…