aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/global_objects/generator/throw/index.html
blob: 19acc2332af63f6a6ded4b32c883b64b3f092e57 (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
94
---
title: Generator.prototype.throw()
slug: Web/JavaScript/Reference/Global_Objects/Generator/throw
tags:
  - ECMAScript6
  - JavaScript
  - 参考
  - 属性
  - 方法
  - 生成器
translation_of: Web/JavaScript/Reference/Global_Objects/Generator/throw
---
<div>{{JSRef}}</div>

<p><code><strong>throw</strong></code><strong><code>()</code></strong> 方法用来向生成器抛出异常,并恢复生成器的执行,返回带有 <code>done</code><code>value</code> 两个属性的对象。</p>

<h2 id="Syntax">语法</h2>

<pre class="syntaxbox"><code><var>gen</var>.throw(exception)</code></pre>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>exception</code></dt>
 <dd>用于抛出的异常。 使用 {{jsxref("Error")}} 的实例对调试非常有帮助.</dd>
</dl>

<h3 id="返回值">返回值</h3>

<p>带有两个属性的{{jsxref("Object", "对象")}}</p>

<ul>
 <li><code>done</code> (boolean)

  <ul>
   <li>如果迭代器已经返回了迭代序列的末尾,则值为 <code>true</code>。在这种情况下,<code>可以</code>指定迭代器 <code>value </code>的返回值。 </li>
   <li>如果迭代能够继续生产在序列中的下一个值,则值为 <code>false</code>。 这相当与不指定 done 属性的值。</li>
  </ul>
 </li>
 <li><code>value</code> - 迭代器返回的任何 JavaScript 值。当 done 是 true 的时候可以省略。</li>
</ul>

<h2 id="示例">示例</h2>

<h3 id="Example:_Using_test">使用 <code>throw()</code></h3>

<p>下面的例子展示了一个简单的生成器并使用 throw方法向该生成器抛出一个异常,该异常通常可以通过 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code> 块进行捕获.</p>

<pre class="brush: js">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!"
</pre>

<h2 id="Specifications">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

{{Compat}}

<h2 id="See_also">相关链接</h2>

<ul>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li>
</ul>