Dart投掷和重新投掷有什么区别?

时间:2020-08-15 03:05:26

标签: flutter exception dart try-catch throw

这也许很明显,但是我仍然无法理解throwrethrow之间的区别,以及什么时候应该使用其中两个?

1 个答案:

答案 0 :(得分:2)

根据Effective Dart

如果您决定重新引发异常,则最好使用rethrow语句,而不要使用throw引发相同的异常对象。 rethrow保留该异常的原始堆栈跟踪。另一方面,throw将堆栈跟踪重置为最后抛出的位置。

最大的区别是保留了原始堆栈跟踪。


他们提供了2个示例来显示预期的用法:

坏:

try {
  somethingRisky();
} catch (e) {
  if (!canHandle(e)) throw e;
  handle(e);
}

好:

try {
  somethingRisky();
} catch (e) {
  if (!canHandle(e)) rethrow;
  handle(e);
}