Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Throw an error into a generator in JavaScript

4 throw() into a running generator

hard

Throw an error into a paused generator so that its own try/catch handles it and it carries on. Then show what happens when the generator has no handler, and when you throw before it has started.

Stuck? Three hints, smallest first
  1. 1. gen.throw(err) raises err at the paused yield, as if that line had thrown.
  2. 2. If the generator catches it, throw() returns the next result object and the generator is still alive.
  3. 3. If it does not, the error comes back out of your throw() call and the generator is finished.

The answer

function* resilient(log) {
  let n = 0;
  while (n < 4) {
    try {
      yield n++;
    } catch (err) {
      log.push('caught ' + err.message);   // recover and keep going
    }
  }
  return 'finished at ' + n;
}

const log = [];
const g = resilient(log);
const started = g.next();
const resumed = g.throw(new Error('bad row'));
const rest = [g.next().value, g.next().value, g.next().value];

// A generator with no try/catch cannot absorb it.
function* fragile() { yield 1; yield 2; }
const f = fragile();
f.next();
const escaped = (() => {
  try { f.throw(new Error('boom')); return 'no throw'; } catch (e) { return e.message; }
})();

// Neither can one that has not started: there is no active try block yet.
const tooSoon = (() => {
  try { resilient([]).throw(new Error('too soon')); return 'no throw'; } catch (e) { return e.message; }
})();

console.log('started :', JSON.stringify(started));
console.log('resumed :', JSON.stringify(resumed), '<- alive, and one value further on');
console.log('log     :', log);
console.log('rest    :', rest);
console.log('no handler inside:', escaped, ' before starting:', tooSoon);

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('it yielded before anything went wrong', started, { value: 0, done: false });
test('throw() raises the error at the paused yield, inside the generator', log, ['caught bad row']);
test('a caught throw leaves the generator alive and moves it on', resumed, { value: 1, done: false });
test('so it still finishes normally', rest, [2, 3, 'finished at 4']);
test('a generator with no handler lets the error back out', escaped, 'boom');
test('and that one is finished', f.next().done, true);
test('throwing before the first next() cannot be caught inside either', tooSoon, 'too soon');

throw() is the mirror of next(): instead of resuming the yield with a value, it resumes it with an exception. That is what lets a consumer report a problem back to the producer — the generator is the one that knows whether the failure is recoverable, so it is the one that should decide.

The two failure cases matter as much as the success. With no try around the yield, the error passes straight through the generator and out of your throw() call, and the generator is left completed. Before the first next() there is no suspended yield at all, so there is nothing to throw at and the error is simply rethrown at you — which is the same shape of surprise as next(value) discarding its argument in exercise 2.

This is the plumbing that async/await was built on. Before it was syntax, await was a library driving a generator: next(resolvedValue) on success, throw(rejection) on failure. Which is precisely why try/catch works around an await.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.