--- title: Generator.prototype.throw() slug: Web/JavaScript/Reference/Global_Objects/Generator/throw tags: - ECMAScript 2015 - Generator - JavaScript - Method - Prototype - Reference translation_of: Web/JavaScript/Reference/Global_Objects/Generator/throw ---
{{JSRef}}

throw() 메서드는 Generator의 실행을 재개시키고 Generator 함수의 실행 문맥 속으로 error를 주입한다. donevalue 프로퍼티를 가진 객체를 반환한다.

구문

gen.throw(exception)

매개변수

exception
Generator 함수의 실행 문맥 속으로 주입할 예외. 디버깅의 목적이라면 instanceof {{jsxref("Error")}} 인 것이 유용하다.

반환 값

두 개의 프로퍼티를 가진 객체

예제

throw() 사용하기

다음의 예시는 간단한 Generator 함수와 throw 메소드를 통해서 주입된 에러를 보여준다. 에러는 try...catch블록을 통해서 핸들링 할 수 있다.

function* gen() {
  while(true) {
    try {
       yield 42;
    } catch(e) {
      console.log("Error caught!");
    }
  }
}

var g = gen();
g.next();
// { value: 42, done: false }
g.throw(new Error("Something went wrong"));
// "Error caught!"
// { value: 42, done: false }

명세

Specification Status Comment
{{SpecName('ES6', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}} {{Spec2('ES6')}} Initial definition.
{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}} {{Spec2('ESDraft')}}  

브라우저 호환성

{{Compat("javascript.builtins.Generator.throw")}}

같이 보기