Skip to content

Fix #13569: Catching undefined constant causes dead catch false positive#5105

Closed
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-xgqj6f7
Closed

Fix #13569: Catching undefined constant causes dead catch false positive#5105
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-xgqj6f7

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

Dynamic class constant fetches like ReactionType::{$name} can throw \Error at runtime when the constant name doesn't exist. PHPStan was reporting a false positive "Dead catch - Error is never thrown in the try block" because no throw point was registered for dynamic class constant fetch expressions.

Changes

  • Added an implicit throw point when processing Expr\ClassConstFetch with a dynamic name ($expr->name instanceof Expr) in src/Analyser/NodeScopeResolver.php
  • Added regression test in tests/PHPStan/Rules/Exceptions/data/bug-13569.php and test method in tests/PHPStan/Rules/Exceptions/CatchWithUnthrownExceptionRuleTest.php

Root cause

In NodeScopeResolver::processExprNode(), when handling Expr\ClassConstFetch, the code correctly processed sub-expressions (the class and name expressions) but did not add an implicit throw point for the fetch itself when the name was dynamic. Since the constant name is determined at runtime, accessing a non-existent constant throws \Error. Without this throw point, the dead catch detection rule incorrectly concluded that \Error could never be thrown in the try block.

Test

The regression test uses an enum with a tryFromName method that uses ReactionType::{$name} inside a try/catch block catching \Error. The test verifies no dead catch error is reported.

Fixes phpstan/phpstan#13569

- Added implicit throw point for dynamic class constant fetch (e.g. Foo::{$name})
- Dynamic class constant fetches can throw \Error at runtime if the constant doesn't exist
- New regression test in tests/PHPStan/Rules/Exceptions/data/bug-13569.php

Closes phpstan/phpstan#13569
Copy link
Contributor

@VincentLanglet VincentLanglet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I already close it because of #5096 (comment)

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.

3 participants