It might be obvious, but I still fail to understand the difference between throw
and rethrow
and when do either of those should be used?
According to Effective Dart:
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.
The biggest difference is the preservation of the original stack trace.
They provided 2 examples to show the intended usage:
Bad:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) throw e;
handle(e);
}
Good:
try {
somethingRisky();
} catch (e) {
if (!canHandle(e)) rethrow;
handle(e);
}