简体   繁体   English

为什么 try..catch..finally 块的 finally 节在 catch 之前运行?

[英]Why does the finally stanza of a try..catch..finally block get run before catch?

try {
  throw new Error('yikes!');
} catch (e) {
  throw e;
} finally {
  console.log('caught error!')
}

Prints out:打印出来:

caught error!
Error: yikes!

So is the finally block running before the throw statement?那么finally块是在 throw 语句之前运行吗?

It only looks like the finally block ran first, but we can see this isn't actually the case:看起来只是 finally 块先运行,但我们可以看到实际情况并非如此:

let failed;

try {
  throw new Error('yikes!');
  failed = false;
} catch (e) {
  failed = true;
  throw e;
} finally {
  console.log(`caught error! failed: ${failed}`)
}

prints印刷

caught error! failed: true
Error: yikes!

So why is the printing of the error out of band?那么为什么错误的打印是带外的呢? is there some asynchronous behaviour here that I'm not seeing?这里有一些我没有看到的异步行为吗?

  1. Try runs - Your try runs and throws the error尝试运行 - 您的尝试运行并抛出错误

  2. Catch runs - Your catch catches the error and simply re-throws it. Catch 运行 - 您的 catch 捕获错误并简单地重新抛出它。

  3. Finally runs - You print out your string最后运行 - 你打印出你的字符串

  4. The rethrown error is now uncaught - And your browser logs details about the error重新抛出的错误现在未被捕获 - 您的浏览器会记录有关该错误的详细信息

The finally clause runs before the overall try block finishes. finally子句在整个try块完成之前运行。 The error that's logged happens when the runtime intercepts the exception, which is after the try block finishes.记录的错误发生在运行时拦截异常时,也就是try块完成之后。 (Note that your catch code does not console.log() anything. It throws a new exception, but the finally clause will still run before the rest of the world sees that.) (请注意,您的catch代码没有console.log()任何内容。它会抛出一个新的异常,但finally子句仍会在世界其他地方看到之前运行。)

All languages with try catch finally that I know of behave in exactly the same way.我所知道的所有带有try catch finally语言都以完全相同的方式运行。 The point of finally blocks is to provide a place to put code that is guaranteed to run whether the try succeeds or fails. finally块的目的是提供一个放置代码的地方,无论try成功还是失败,都可以保证运行。

The throw statement doesn't print anything. throw语句不打印任何内容。 The error is printed later when the browser catches the thrown error.当浏览器捕获到抛出的错误时,该错误会在稍后打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM