2024-07-18 13:20:47 +02:00
== Why is this an issue?
In dart `throw` is used no initiate an exception. Usually this is enough to just catch it and handle. However, there are cases when the exceptions needs to be propagated further after being caught. This allows a handling of the exception on different levels.
In such case it's recommended to use `rethrow` instead of just `throw`, to preserve the original stacktrace.
[source,dart]
----
try {
...
2024-08-06 17:50:08 +02:00
} catch (ex) {
rethrow; // preserves the original exception with its stacktrace
2024-07-18 13:20:47 +02:00
}
----
== How to fix it
The rule raises an issue when the argument of the `throw` expression is an unmodified copy of the caught exception.
=== Code examples
==== Noncompliant code example
[source,dart,diff-id=1,diff-type=noncompliant]
----
void foo() {
try {
methodThrowsException();
} catch (ex) {
// ...
throw ex; // Noncompliant
}
}
----
==== Compliant solution
[source,dart,diff-id=1,diff-type=compliant]
----
void foo() {
try {
methodThrowsException();
} catch (ex) {
// ...
2024-08-06 17:50:08 +02:00
rethrow;
2024-07-18 13:20:47 +02:00
}
}
----
== Resources
2024-08-06 17:50:08 +02:00
* Dart Docs - https://dart.dev/tools/linter-rules/use_rethrow_when_possible[Dart Linter rule - use_rethrow_when_possible]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use 'rethrow' to rethrow a caught exception.
=== Highlighting
The `throw` statement with the argument.
'''
endif::env-github,rspecator-view[]