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?
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);
}