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
rethrowstatement instead of throwing the same exception object usingthrow.rethrowpreserves the original stack trace of the exception.throwon 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With