Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False positive for undefined variable in try-catch-finally #5967

Open
Radiergummi opened this issue Jun 21, 2021 · 3 comments · May be fixed by #7688
Open

False positive for undefined variable in try-catch-finally #5967

Radiergummi opened this issue Jun 21, 2021 · 3 comments · May be fixed by #7688

Comments

@Radiergummi
Copy link

This is probably related to #5123, but a more general case:
https://psalm.dev/r/17c2685cb3

In all possible code paths, the variable will be defined.

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/17c2685cb3
<?php

function f(): int {
    try {
        $x = 10;
    } catch (Throwable $e) {
        $x = 20;
    } finally {
        return $x;
    }
}
Psalm output (using commit 52d2692):

INFO: PossiblyUndefinedVariable - 9:16 - Possibly undefined variable $x defined in try block

@weirdan
Copy link
Collaborator

weirdan commented Jun 21, 2021

That works only for catch(Throwable), catching any other descendant of Throwable instead would leave $x potentially undefined.

@Radiergummi
Copy link
Author

Radiergummi commented Jun 21, 2021

Yup - or if $x is defined in all catch blocks for any exception the try block may throw. A concrete (if a little contrived) example would be something like this:

$start = microtime(true);

try {
  HttpClient::request($req);
  $duration = microtime(true) - $start;
} catch (HttpExeption $e) {
  // ...
  $duration = microtime(true) - $start;
} catch (Throwable $e) {
  $duration = 0;
} finally {
  Log::debug(sprintf('Request took %0.2fs', $duration));
}

In every code path, duration will be defined at the time the code in finally is executed.

@AndrolGenhald AndrolGenhald linked a pull request Feb 17, 2022 that will close this issue
@weirdan weirdan linked a pull request Feb 20, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants