dart-lang / linter

Linter for Dart.
https://dart.dev/tools/linter-rules
BSD 3-Clause "New" or "Revised" License
628 stars 170 forks source link

[use_rethrow_when_possible] False positive in a switch expression #4919

Closed Levi-Lesches closed 5 months ago

Levi-Lesches commented 6 months ago

Describe the issue

Rethrowing is supported in switch statements, but not switch expressions.

However, the lint still suggests to replace throw error with rethrow

To Reproduce

int getValue() => throw "Error2";

void main() {
  try {
    getValue();
  } catch (error) {
    final message = switch(error) {
      "Error1" => "Error 1",
      "Error2" => "Error 2",
      _ => throw error,
    };
    print(message);
  }
}

Expected behavior The lint should not appear.

Additional context Given that throw error is allowed, I'm still not sure why rethrow shouldn't be. cc @munificent from the linked issue.

munificent commented 6 months ago

Given that throw error is allowed, I'm still not sure why rethrow shouldn't be.

It's a language limitation. The bodies of switch expressions are expressions. Many years ago, we made throw an expression (mainly so you could use it as the body of =>-bodied methods), but we never turned rethrow into an expression. We probably should: https://github.com/dart-lang/language/issues/3097.

lrhn commented 6 months ago

I think the lint should appear in this case. It (currently) requires you to rewrite the switch, but you probably should do that, so that the error is rethrown with the correct stack trace.

But we should make rethrow an expression. And return, break and continue too, because we can.

srawlins commented 5 months ago

Fixed by https://github.com/dart-lang/sdk/commit/51088718e194b6f8f97ff0faf41fa9f8a0dea28a