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);
}
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 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.
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.
© 2022 - 2024 — McMap. All rights reserved.