The generator.throw() method in JavaScript.

The generator.throw() method allows you to inject an error into a generator function at the current yield point. When called, it throws the specified error inside the generator and returns an object with done and value properties.

Syntax

generator.throw(exception)

Parameters

exception: The error object to be thrown inside the generator function.

Basic Example

function* simpleGenerator() {
    try {
        console.log("Before first yield");
        yield 1;
        console.log("After first yield");
        yield 2;
    } catch (error) {
        console.log("Caught error:", error.message);
    }
    console.log("Generator continues");
    yield 3;
}

const gen = simpleGenerator();

console.log(gen.next().value);  // First yield
console.log(gen.throw(new Error("Test error")).value);  // Throw error
console.log(gen.next().value);  // Continue after error
Before first yield
1
Caught error: Test error
Generator continues
3
undefined

Interactive Browser Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator Throw Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        .output {
            background: #f0f0f0;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            background: #007bff;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>Generator throw() Method Demo</h1>
    <div class="output" id="output">Click buttons to interact with generator</div>
    <button onclick="getNextValue()">Get Next Value</button>
    <button onclick="throwError()">Throw Error</button>
    <button onclick="resetGenerator()">Reset</button>

    <script>
        function* counterGenerator() {
            let count = 1;
            while (count <= 5) {
                try {
                    console.log(`About to yield: ${count}`);
                    yield count++;
                    console.log("Resumed after yield");
                } catch (error) {
                    document.getElementById('output').innerHTML += 
                        `<div class="error">Error caught: ${error.message}</div>`;
                    console.log("Error handled, continuing...");
                }
            }
            return "Generator finished";
        }

        let generator = counterGenerator();

        function getNextValue() {
            const result = generator.next();
            const output = document.getElementById('output');
            
            if (result.done) {
                output.innerHTML += `<div>${result.value}</div>`;
            } else {
                output.innerHTML += `<div>Yielded: ${result.value}</div>`;
            }
        }

        function throwError() {
            try {
                const result = generator.throw(new Error("Custom error thrown!"));
                const output = document.getElementById('output');
                
                if (!result.done) {
                    output.innerHTML += `<div>After error - Yielded: ${result.value}</div>`;
                }
            } catch (error) {
                document.getElementById('output').innerHTML += 
                    `<div class="error">Unhandled error: ${error.message}</div>`;
            }
        }

        function resetGenerator() {
            generator = counterGenerator();
            document.getElementById('output').innerHTML = "Generator reset. Click buttons to start.";
        }
    </script>
</body>
</html>

Error Handling Without try-catch

If the generator doesn't have a try-catch block, the thrown error propagates outside:

function* noErrorHandling() {
    yield 1;
    yield 2;  // This won't be reached if error is thrown
    yield 3;
}

const gen2 = noErrorHandling();
console.log(gen2.next().value);  // 1

try {
    gen2.throw(new Error("Unhandled error"));
} catch (error) {
    console.log("Error caught outside generator:", error.message);
}

// Generator is now in completed state
console.log(gen2.next().done);  // true
1
Error caught outside generator: Unhandled error
true

Key Points

  • throw() injects an error at the current yield point
  • If the generator has try-catch, it can handle the error and continue
  • Without error handling, the error propagates and terminates the generator
  • Returns an object with {value, done} properties like next()

Conclusion

The generator.throw() method provides a way to inject errors into generators for testing error conditions and implementing robust error handling in generator-based control flows.

Updated on: 2026-03-15T23:18:59+05:30

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements