We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7d5a562 commit 2d86fc3Copy full SHA for 2d86fc3
docs/generator.md
@@ -534,6 +534,24 @@ g.throw();
534
535
上面代码中,`g.throw`抛出错误以后,没有任何`try...catch`代码块可以捕获这个错误,导致程序报错,中断执行。
536
537
+`throw`方法抛出的错误要被内部捕获,前提是必须至少执行过一次`next`方法。
538
+
539
+```javascript
540
+function* gen() {
541
+ try {
542
+ yield 1;
543
+ } catch (e) {
544
+ console.log('内部捕获');
545
+ }
546
+}
547
548
+var g = gen();
549
+g.throw(1);
550
+// Uncaught 1
551
+```
552
553
+上面代码中,`g.throw(1)`执行时,`next`方法一次都没有执行过。这时,抛出的错误不会被内部捕获,而是直接在外部抛出,导致程序出错。这种行为其实很好理解,因为第一次执行`next`方法,等同于启动执行 Generator 函数的内部代码,否则 Generator 函数还没有开始执行,这时`throw`方法抛错只可能抛出在函数外部。
554
555
`throw`方法被捕获以后,会附带执行下一条`yield`表达式。也就是说,会附带执行一次`next`方法。
556
557
```javascript
0 commit comments