Skip to main content

What does the throw operator do?

Definition

throw is an operator that interrupts the execution of the current code and throws an exception (an error or any other object).

Syntax

javascript
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

javascript
throw "Something went wrong!";

In the console:

javascript
Uncaught Something went wrong!

Here the program stops immediately, because the exception was not caught.

Example 2. With a try...catch block

javascript
try { throw new Error("An error occurred during execution!"); } catch (err) { console.log("Caught:", err.message); }

What happens:

  1. throw creates an exception - an Error object.
  2. Execution of try is interrupted.
  3. Control passes to catch.
  4. The error is handled, the program continues.

Output:

javascript
Caught: An error occurred during execution!

Example 3. Using throw to validate input data

javascript
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:

javascript
Error: Division by zero is not possible!

Example 4. You can throw more than just Error

javascript
try { throw { message: "Network error", code: 500 }; } catch (e) { console.log(e.message, e.code); }

Output:

javascript
Network error 500

But 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

javascript
console.log("before throw"); throw new Error("error!"); console.log("after throw"); // will not run

After throw, execution of the current block stops, and control passes to an error handler (if one exists).

Visually

javascript
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

PointDescription
PurposeForcibly throws an exception (an error)
Value typeAny data type can be thrown (usually Error)
EffectInterrupts execution of the current block
Used withtry...catch to handle errors
After throwThe code that follows does not run

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.