Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart What is the difference between throw and rethrow?

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?


1 Answers

According to Effective Dart:

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.

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);
}
like image 191
Christopher Moore Avatar answered Dec 24 '25 15:12

Christopher Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!