What does the throw operator do?
Definition
throwis an operator that interrupts the execution of the current code and throws an exception (an error or any other object).
Syntax
throw expression;Where expression can be any JS value:
an object, a number, a string, a boolean, and so on.
But most often an instance of the Error class is thrown.
Example 1. Simple usage
throw "Something went wrong!";In the console:
Uncaught Something went wrong!Here the program stops immediately, because the exception was not caught.
Example 2. With a try...catch block
try {
throw new Error("An error occurred during execution!");
} catch (err) {
console.log("Caught:", err.message);
}What happens:
throwcreates an exception - anErrorobject.- Execution of
tryis interrupted. - Control passes to
catch. - The error is handled, the program continues.
Output:
Caught: An error occurred during execution!Example 3. Using throw to validate input data
function divide(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new TypeError("Both arguments must be numbers!");
}
if (b === 0) {
throw new Error("Division by zero is not possible!");
}
return a / b;
}
try {
console.log(divide(5, 0));
} catch (e) {
console.error("Error:", e.message);
}Output:
Error: Division by zero is not possible!Example 4. You can throw more than just Error
try {
throw { message: "Network error", code: 500 };
} catch (e) {
console.log(e.message, e.code);
}Output:
Network error 500But this is usually not recommended - it is better to always use the standard error classes (Error, TypeError, RangeError, and so on) to keep things readable and compatible.
Example 5. Code after throw does not run
console.log("before throw");
throw new Error("error!");
console.log("after throw"); // will not runAfter throw, execution of the current block stops, and control passes to an error handler (if one exists).
Visually
try {
// throw an exception
throw new Error("Error!");
} catch (e) {
// catch the exception
console.log("Caught:", e.message);
} finally {
console.log("This block always runs");
}Summary
| Point | Description |
|---|---|
| Purpose | Forcibly throws an exception (an error) |
| Value type | Any data type can be thrown (usually Error) |
| Effect | Interrupts execution of the current block |
| Used with | try...catch to handle errors |
| After throw | The code that follows does not run |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.