JavaScript Notes
Learn the JavaScript throw statement: throw Error objects, custom error classes, validation guards, and best practices for intentional error signaling with interview Q&A.
The throw statement intentionally signals an error — it stops the current function, skips all subsequent code, and transfers control to the nearest catch block. It is how you say "something is wrong, I cannot continue."
Think of throw as a fire alarm — it stops everything, sends a signal, and lets whoever is in charge (the catch block) handle the situation.
📊 Throw Flow Diagram
💻 Example 1 — Basic throw with Error Object
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero"); // intentional error
}
return a / b;
}
try {
console.log(divide(10, 2));
console.log(divide(10, 0)); // throws
console.log(divide(8, 4)); // never reached
} catch (error) {
console.log("Caught:", error.message);
}5 Caught: Cannot divide by zero
💻 Example 2 — Throw Specific Error Types
Created: { name: 'Riya', age: 22, email: 'riya@wohotech.in' }
TypeError: age must be a number
RangeError: age must be between 0 and 150💻 Example 3 — Guard Clauses (Fail Fast Pattern)
Guard clauses use throw at the top of a function to validate inputs immediately — keeping the "happy path" clean and readable.
✅ Processing ₹1500 INR for account ACC-001 RangeError: Amount must be positive, got -100 RangeError: Unsupported currency: BTC
💻 Example 4 — Rethrowing Errors
Sometimes you catch an error, add context, and rethrow it for a higher-level handler to deal with.
App startup error: Config load failed [missing.json]: File not found
📋 throw Best Practices
| Practice | Why |
|---|---|
Throw Error objects, not strings | Error objects have .stack for debugging |
Use specific types (TypeError, RangeError) | Callers can handle different errors differently |
| Include the bad value in the message | "Expected string, got number (42)" is more useful than "wrong type" |
| Throw early (guard clauses) | Prevents deeper code from running with invalid data |
| Rethrow with added context | Helps with debugging in nested calls |
Never throw null or undefined | Makes error handling impossible |
⚠️ Common Mistakes
❌ Mistake 1 — Throwing Strings Instead of Error Objects
// BAD — no stack trace, no error type
function bad(x) {
throw "Input is invalid"; // caller gets a string, not an Error
}
try { bad(null); } catch (e) {
console.log(typeof e); // "string" — can't call e.message or e.stack
console.log(e.message); // undefined!
}string undefined
// GOOD — use Error objects
function good(x) {
throw new Error("Input is invalid");
}
try { good(null); } catch (e) {
console.log(e.message); // "Input is invalid"
console.log(e.stack); // full stack trace
}❌ Mistake 2 — Throwing Without a Message
// BAD — unhelpful for debugging
if (!user) throw new Error();
// GOOD — descriptive message
if (!user) throw new Error(`User with id=${id} not found`);❌ Mistake 3 — Throwing Instead of Returning in Validation Helpers
For simple validation, returning false or a result is more appropriate than throwing. Reserve throw for truly exceptional conditions that the caller cannot easily predict.
// BAD for simple validation
function isEmailValid(email) {
if (!email.includes("@")) throw new Error("Invalid"); // caller must use try-catch just to validate
return true;
}
// GOOD for simple validation
function isEmailValid(email) { return email.includes("@"); } // returns boolean🎯 Key Takeaways
throwimmediately stops the function and propagates the error up the call stack- Always throw
Errorobjects (or subclasses) — never throw strings or numbers - Use specific types:
TypeError(wrong type),RangeError(out-of-bounds),Error(general) - Use guard clauses with
throwat the top of functions to validate inputs early - You can
throwinside acatchblock to rethrow with added context - Include the bad value in the error message:
"Expected number, got string: '42'" throwis for exceptional conditions — use return values for expected outcomes
❓ Interview Questions
Q1. What does throw do in JavaScript? > throw immediately stops the current function execution and propagates an error up the call stack to the nearest catch block. If no catch handles it, the program crashes with an "Uncaught Error" message.
Q2. What is the difference between throw new Error("msg") and throw "msg"? > throw new Error("msg") creates an Error object with .message, .name, and .stack properties — valuable for debugging. throw "msg" throws a plain string — no stack trace, no type, much harder to debug. Always use Error objects.
Q3. When should you use throw? > Use throw when a function receives invalid input it cannot handle, when a required resource is missing, when a business rule is violated, or when you need to signal to callers that something is genuinely exceptional and they must handle it.
Q4. What is a guard clause? > A guard clause is an early throw (or return) at the top of a function that validates inputs before the main logic runs. It keeps functions readable by handling edge cases first, leaving the "happy path" clean and unindented.
Q5. Can you throw inside a catch block? > Yes — this is called "rethrowing." You catch an error, optionally add context to it, then throw it again for a higher-level handler. This pattern helps separate low-level error detection from high-level recovery logic.
Q6. What is the difference between throw new TypeError() and throw new Error()? > TypeError signals that the wrong type of value was provided. Error is the generic base. Using specific types allows catch blocks to use instanceof to handle different errors differently — e.g., retry on network errors, show user message on validation errors.
Q7. Does throw work inside async functions? > Yes. throw inside an async function causes the returned Promise to reject. The caller should await the call inside try...catch to handle it.
Q8. What happens if no catch block handles a thrown error? > The error propagates up the call stack. If it reaches the top with no handler, in browsers it becomes an "Uncaught Error" in the console. In Node.js, it triggers an uncaughtException event, which can crash the process if not handled.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript throw Statement – Throw Errors, Custom Messages & Error Types.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, error, handling, throw
Related JavaScript Master Course Topics