blob: 637a599b23b1a8f5dd08ffcd60c7689963dd0713 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
---
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
---
<div>{{JSRef}}</div>
<p><span class="seoSummary"><strong><code>throw()</code></strong> メソッドは、ジェネレーターの例外を、エラーを発生させることで再開し、 <code>done</code> と <code>value</code> の2つのプロパティを持ったオブジェクトを返します。</span></p>
<h2 id="Syntax" name="Syntax">構文</h2>
<pre class="syntaxbox notranslate"><code><var>gen</var>.throw(<var>exception</var>)</code></pre>
<h3 id="Parameters" name="Parameters">引数</h3>
<dl>
<dt><code><var>exception</var></code></dt>
<dd>発生させる例外。デバッグ時には <code>instanceof</code> {{jsxref("Error")}} を行うと便利です。</dd>
</dl>
<h3 id="Return_value" name="Return_value">返値</h3>
<p>2つのプロパティを持つ {{jsxref("Global_Objects/Object", "Object")}} です。</p>
<dl>
<dt><code>done</code> (boolean)</dt>
<dd>
<ul>
<li>イテレーターが反復処理の末尾を過ぎている場合、値は <code>true</code> になります。この場合、 <code>value</code> はオプションでそのイテレーターの<em>返値</em>を指定します。</li>
<li>イテレーターが反復処理の次の値を生成することができた場合、値は <code>false</code> になります。これは <code>done</code> プロパティを指定しない場合も同等です。</li>
</ul>
</dd>
<dt><code>value</code></dt>
<dd>イテレーターが返す何らかの JavaScript の値です。 <code>done</code> が <code>true</code> の場合は省略可能です。</dd>
</dl>
<h2 id="Examples" name="Examples">例</h2>
<h3 id="Using_throw" name="Using_throw">throw() の使用</h3>
<p>次の例では、簡単なジェネレーターと、 <code>throw</code>メソッドを用いて発生させるエラーを示します。エラーは通常 {{jsxref("Statements/try...catch", "try...catch")}} ブロックによって受け取られます。</p>
<pre class="brush: js notranslate">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 }
</pre>
<h2 id="Specifications" name="Specifications">仕様書</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">仕様書</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2>
<div>
<p>{{Compat("javascript.builtins.Generator.throw")}}</p>
</div>
<h2 id="See_also" name="See_also">関連情報</h2>
<ul>
<li>{{jsxref("Statements/function*", "function*")}}</li>
</ul>
|