Dart What is the difference between throw and rethrow?
Asked Answered
M

3

13

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?

Megdal answered 15/8, 2020 at 3:5 Comment(0)
P
26

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);
}
Parmer answered 15/8, 2020 at 3:43 Comment(4)
That is exactly what I found when looking on Google, still didn't understand, when I looked are ResoCoder's video on handling exception I got all the more confused.Megdal
@TersterWordp What don't you understand?Parmer
If I used throw e instead of rethrow what would change in the stackTrace? Could you provide a personal example of when you would use either of those?Megdal
@TersterWordp This question shows an example of where the original stacktrace is lost and the answer shows how rethrow preserves it. Just trying something like this and looking at the difference in stacktraces will make it obvious.Parmer
T
3

It's abit late to respond but I guess it will help someone at the present or in the future. Throw and Rethrow for Handling Exceptions.

throw keyword is used when you encounter an exception and you intiate a process of raising an exception just within you code. More of signaling that an exception has occured.

rethrow keyword is used when you want to propagate your exception up the stack. More like you catch an exception and perform some handling and propagate to a higher level handler which is within the stack.

Summry

throw

  • Is used in the creation and signaling of an exception.

rethrow

  • Is used where an exception is caught and probably handled at a point considered low level and then propagate the same exception to a higher level handler.
  • Good in handling exceptions at multiple levels, and still preserving the original exception, valuable for debugging and troubleshooting.
Tolle answered 2/10, 2023 at 14:6 Comment(0)
U
0

throw is used to initiate an exception. It can be used anywhere in your code where an exception is appropriate.

rethrow is used within a catch block to rethrow an exception that was caught. It allows you to handle an exception at one level of the call stack and then pass it up for further handling.

Untie answered 10/5 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.