What the throw statement does
throw is a statement that interrupts the execution of the current code and throws an exception: an error or any other object. It turns an ordinary value into an error event that try...catch then catches, and if there is nothing to catch it, the exception bubbles up the stack and terminates the program.
Theory
TL;DR
throw expression;forcibly raises an exception and cuts the current block short.- You can throw any value, but the right thing to throw is an
Erroror a subclass of it. - Control passes to the nearest
catch; without one the exception stays uncaught. - Code written after
throwin the same block will never run. throwis the main tool for validating function input.
Quick example
try {
throw new Error("Something went wrong during execution");
} catch (err) {
console.log("Caught:", err.message);
}
// Caught: Something went wrong during executionSyntax and what exactly you can throw
The syntax is as short as it gets:
throw expression;Here expression can be any JavaScript value: an object, a number, a string, a boolean and so on. Most often, though, what gets thrown is an instance of the Error class.
The simplest use:
throw "Something went wrong";In the console:
Uncaught Something went wrongThe program stops immediately here, because the exception was not caught.
You can also throw a plain object:
try {
throw { message: "Network error", code: 500 };
} catch (e) {
console.log(e.message, e.code);
}
// Network error 500But this is not recommended: always prefer the standard error classes (Error, TypeError, RangeError and so on) to keep readability, compatibility and the call stack.
throw together with try / catch / finally
When throw fires inside try, this is what happens:
throwcreates an exception, usually anErrorobject.- Execution of the
tryblock is interrupted at that line. - Control is handed to
catch. - The error is handled and the program continues.
try {
// throw the exception
throw new Error("Failure");
} catch (e) {
// catch the exception
console.log("Caught:", e.message);
} finally {
console.log("This block always runs");
}The finally block runs in either case: whether there was an exception or not.
Validating input with throw
The most common practical scenario is validating function arguments:
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 allowed");
}
return a / b;
}
try {
console.log(divide(5, 0));
} catch (e) {
console.error("Error:", e.message);
}
// Error: Division by zero is not allowedNote the choice of class: a wrong argument type naturally calls for TypeError, a value outside the allowed range for RangeError, and a domain failure for your own subclass of Error.
Code after throw does not run
throw acts as an immediate exit from the block:
console.log("before throw");
throw new Error("failure");
console.log("after throw"); // will not runAfter throw, execution of the current block stops, and control is passed to the error handler, if there is one.
Summary
| Item | 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 for error handling |
| After throw | The code that follows does not run |
Common mistakes
- Throwing a string instead of an
Error.throw "text"deprives you ofstackandname, and monitoring tools will not report such an exception properly. - Writing code after
throw. Everything that follows it in the same block is dead code that will never execute. - Confusing
throwandreturn.returnhands a value back to the caller,throwunwinds the stack until it finds acatch. - Throwing inside an asynchronous callback. A
throwin asetTimeoutcallback will not reach the surroundingtry...catch, because that block has already finished. - Swallowing the exception with an empty
catch. Once you catch it, either handle it or rethrow withthrow err, otherwise the cause of the failure disappears.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.