diff --git a/CHANGELOG.md b/CHANGELOG.md index 23755236bc7..998c0542e2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug fixes * [#8720](https://github.com/rubocop-hq/rubocop/issues/8720): Fix an error for `Lint/IdentityComparison` when calling `object_id` method without receiver in LHS or RHS. ([@koic][]) +* [#8767](https://github.com/rubocop-hq/rubocop/issues/8767): Fix a false positive for `Style/RedundantReturn` when a rescue has an else clause. ([@fatkodima][]) * [#8710](https://github.com/rubocop-hq/rubocop/issues/8710): Fix a false positive for `Layout/RescueEnsureAlignment` when `Layout/BeginEndAlignment` cop is not enabled status. ([@koic][]) * [#8726](https://github.com/rubocop-hq/rubocop/issues/8726): Fix a false positive for `Naming/VariableNumber` when naming multibyte character variable name. ([@koic][]) * [#8730](https://github.com/rubocop-hq/rubocop/issues/8730): Fix an error for `Lint/UselessTimes` when there is a blank line in the method definition. ([@koic][]) diff --git a/lib/rubocop/cop/style/redundant_return.rb b/lib/rubocop/cop/style/redundant_return.rb index 63de3759f57..b9151f8f811 100644 --- a/lib/rubocop/cop/style/redundant_return.rb +++ b/lib/rubocop/cop/style/redundant_return.rb @@ -108,8 +108,8 @@ def check_branch(node) when :return then check_return_node(node) when :case then check_case_node(node) when :if then check_if_node(node) - when :rescue, :resbody - check_rescue_node(node) + when :rescue then check_rescue_node(node) + when :resbody then check_resbody_node(node) when :ensure then check_ensure_node(node) when :begin, :kwbegin check_begin_node(node) @@ -137,9 +137,12 @@ def check_if_node(node) end def check_rescue_node(node) - node.child_nodes.each do |child_node| - check_branch(child_node) - end + node.branches.each { |branch| check_branch(branch) } + check_branch(node.body) unless node.else? + end + + def check_resbody_node(node) + check_branch(node.body) end def check_ensure_node(node) diff --git a/spec/rubocop/cop/style/redundant_return_spec.rb b/spec/rubocop/cop/style/redundant_return_spec.rb index 466d60d2237..8f6a33addd1 100644 --- a/spec/rubocop/cop/style/redundant_return_spec.rb +++ b/spec/rubocop/cop/style/redundant_return_spec.rb @@ -344,6 +344,27 @@ def func end RUBY end + + it 'registers an offense and corrects when rescue has else clause' do + expect_offense(<<~RUBY) + def func + return 3 + rescue SomeException + else + return 4 + ^^^^^^ Redundant `return` detected. + end + RUBY + + expect_correction(<<~RUBY) + def func + return 3 + rescue SomeException + else + 4 + end + RUBY + end end context 'when return is inside an if-branch' do