Throwing Exceptions in JavaScript
🧠 What Does "Throwing an Exception" Mean?
In JavaScript, throw is used to manually generate an error (i.e., throw an exception) when something goes wrong or when you want to signal that the code cannot proceed normally.
This thrown error can then be caught using a try...catch block and handled appropriately. It's a key part of robust error handling. 🛡️
🛠️ Syntax
Code Snippet
throw expression;Note
The expression can be any JavaScript value, but it's recommended to throw an Error object for consistency and debugging.
📦 Example: Throwing an Error
Code Snippet
function withdraw(amount) {
if (amount > 1000) {
throw new Error("Withdrawal limit exceeded 💸");
}
console.log("Withdrawal successful ✅");
}
try {
withdraw(1500);
} catch (err) {
console.error("Transaction failed:", err.message);
}⚠️ Throwing Different Types
JavaScript allows you to throw various types:
- throw "Something went wrong"; → string
- throw 404; → number
- throw true; → boolean
- throw new Error("Message"); → ✅ preferred way
Note
🧠 Best practice is to always throw Error objects. This includes helpful metadata like the stack trace.
📚 Built-in Error Types
JavaScript includes several built-in error constructors:
- Error: Generic error
- TypeError: Wrong type used
- ReferenceError: Invalid variable reference
- SyntaxError: Invalid JavaScript syntax
- RangeError: Value out of allowed range
- URIError: Invalid URI usage
Code Snippet
throw new TypeError("Expected a string");🔄 Custom Error Class
You can define your own custom error types for better debugging:
Code Snippet
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 18) throw new ValidationError("Must be at least 18 years old");
}
try {
validateAge(15);
} catch (e) {
console.error(e.name + ":", e.message);
}🚫 Where You Can’t Throw
- Outside of function calls in eval
- Without a valid expression (e.g., just throw without value causes SyntaxError)
📌 Best Practices
- ✅ Always throw Error objects (or subclasses)
- 🔒 Use try...catch to manage and handle errors
- 🔍 Include helpful error messages for debugging
📚 References
>>“Don’t let your app silently fail — throw an exception and handle it wisely.”