--- 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()
メソッドは、ジェネレーターの例外を、エラーを発生させることで再開し、 done
と value
の2つのプロパティを持ったオブジェクトを返します。
gen.throw(exception)
exception
instanceof
{{jsxref("Error")}} を行うと便利です。2つのプロパティを持つ {{jsxref("Global_Objects/Object", "Object")}} です。
done
(boolean)true
になります。この場合、 value
はオプションでそのイテレーターの返値を指定します。false
になります。これは done
プロパティを指定しない場合も同等です。value
done
が true
の場合は省略可能です。次の例では、簡単なジェネレーターと、 throw
メソッドを用いて発生させるエラーを示します。エラーは通常 {{jsxref("Statements/try...catch", "try...catch")}} ブロックによって受け取られます。
function* gen() { while(true) { try { yield 42; } catch(e) { console.log('Error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new Error('Something went wrong')); // "Error caught!" // { value: 42, done: false }
仕様書 |
---|
{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}} |
{{Compat("javascript.builtins.Generator.throw")}}