--- 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 ---
throw()
메서드는 Generator의 실행을 재개시키고 Generator 함수의 실행 문맥 속으로 error를 주입한다. done
과 value
프로퍼티를 가진 객체를 반환한다.
gen.throw(exception)
exception
instanceof
{{jsxref("Error")}} 인 것이 유용하다.두 개의 프로퍼티를 가진 객체
done
(boolean)
true
. 만약 iterator(반복자)에 return 값이 있다면 value
의 값으로 지정된다.false
. Iterator(반복자)에 done
프로퍼티 자체를 특정짓지 않은 것과 동일하다.value
- Iterator(반복자)으로부터 반환되는 모든 자바스크립트 값이며 done
이 true
일 경우 생략될 수 있다.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")}}