Skip to content

Fix phpstan/phpstan#6119: False positive in try/catch/finally when throwing exception inside try block#5340

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-4r5qcpx
Open

Fix phpstan/phpstan#6119: False positive in try/catch/finally when throwing exception inside try block#5340
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-4r5qcpx

Conversation

@phpstan-bot
Copy link
Copy Markdown
Collaborator

Summary

When a throw inside a try block is caught by a catch block, PHPStan incorrectly reported it as "overwritten by a different one in the finally block below." The throw is handled by the catch, so it is not an exit point that the finally block overwrites.

Changes

  • Modified src/Analyser/NodeScopeResolver.php: deferred adding try body throw exit points to $finallyExitPoints until after catch blocks are processed. Only uncaught throws (those still present in $throwPoints after catch processing) are added.
  • Updated test expectations in tests/PHPStan/Rules/Exceptions/OverwrittenExitPointByFinallyRuleTest.php for testRule and testBug5627 to remove caught throw exit points that are no longer reported.
  • Added regression test tests/PHPStan/Rules/Exceptions/data/bug-6119.php.

Root cause

In NodeScopeResolver.php, try body throw exit points were unconditionally added to $finallyExitPoints before catch blocks were processed. This meant that even throws fully caught by catch blocks were reported as overwritten by the finally block. The fix collects try body throw exit points separately, processes catch blocks first, then checks whether each throw point was consumed (caught) during catch processing. Only uncaught throws are added to $finallyExitPoints.

Test

Added tests/PHPStan/Rules/Exceptions/data/bug-6119.php which reproduces the original issue: a throw inside a try block caught by catch(\Throwable) with a finally { return 'OK'; }. The test expects no errors (empty array), confirming the false positive is eliminated.

Fixes phpstan/phpstan#6119

…rowing inside try block

- Throw exit points from try body that are caught by catch blocks are no longer reported as overwritten by finally
- Deferred adding try body throw exit points to finallyExitPoints until after catch processing
- After catches are processed, only uncaught throws are added to finallyExitPoints
- Updated existing test expectations in testRule and testBug5627 to reflect correct behavior
- New regression test in tests/PHPStan/Rules/Exceptions/data/bug-6119.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant