Dart throw 和 rethrow 有什么区别?
Dart What is the difference between throw and rethrow?
这可能很明显,但我仍然无法理解 throw
和 rethrow
之间的区别,以及何时应该使用它们中的任何一个?
If you decide to rethrow an exception, prefer using the rethrow
statement instead of throwing the same exception object using throw
. rethrow
preserves the original stack trace of the exception. throw
on the other hand resets the stack trace to the last thrown position.
最大的不同是保留了原始堆栈跟踪。
他们提供了 2 个示例来说明预期用途:
差:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) throw e;
handle(e);
}
好:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) rethrow;
handle(e);
}
这可能很明显,但我仍然无法理解 throw
和 rethrow
之间的区别,以及何时应该使用它们中的任何一个?
If you decide to rethrow an exception, prefer using the
rethrow
statement instead of throwing the same exception object usingthrow
.rethrow
preserves the original stack trace of the exception.throw
on the other hand resets the stack trace to the last thrown position.
最大的不同是保留了原始堆栈跟踪。
他们提供了 2 个示例来说明预期用途:
差:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) throw e;
handle(e);
}
好:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) rethrow;
handle(e);
}