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

Not all code paths end in a return statement error when using try/catch inside loop #7842

Closed
theodorejb opened this issue Apr 4, 2022 · 4 comments

Comments

@theodorejb
Copy link
Contributor

This function always returns an int, but Psalm outputs an InvalidReturnType error:

https://psalm.dev/r/f5300a45a7

If I add an extra return 0 at the end of the function to make Psalm happy, then PhpStorm (rightly) shows a warning that the statement is unreachable.

I expect that this should work in Psalm without an error, since similar issues like #4245 and #4327 have previously been fixed.

@psalm-github-bot
Copy link

I found these snippets:

https://psalm.dev/r/f5300a45a7
<?php

function retry(): int {
    do {
        try {
			return mayThrow();
        } catch (Exception $e) {
            if ($e->getMessage() === 'Result was 0') {
                continue;
            }
        }
    } while (true);
}

function mayThrow(): int
{
    $res = random_int(0, 1);

    if ($res === 1) {
        return $res;
    }

    throw new Exception("Result was {$res}");
}
Psalm output (using commit cab6f33):

ERROR: InvalidReturnType - 3:19 - Not all code paths of retry end in a return statement, return type int expected

@AndrolGenhald
Copy link
Collaborator

I have an open PR with a lot of try/catch improvements, but unfortunately it's blocked by some other issues and I'm short on time lately. I'll see if I can work this in there before it's merged.

@edsrzf
Copy link
Contributor

edsrzf commented Mar 15, 2023

It looks like this was fixed at some point. The snippet link no longer has any errors.

@theodorejb
Copy link
Contributor Author

Indeed, this was fixed by #8929, released in Psalm 5.3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants