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

return in finally can swallow exception #1231

Open
iritkatriel opened this issue Oct 22, 2024 · 2 comments
Open

return in finally can swallow exception #1231

iritkatriel opened this issue Oct 22, 2024 · 2 comments

Comments

@iritkatriel
Copy link

In the expr_match function:

def expr_match(ob, ed, c=InstanceDict, r=0):
    e, md, push, pop = ed
    push(c(ob, md))
    try:
        r = e.eval(md)
    finally:
        pop()
        return r

The return in the finally will swallow any in-flight exception. This means that if r.eval(md) raises any exception (including KeyboardInterrupt), this exception will be swallowed. This is probably not what the author intended.

See also: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions.

It is possible that the intention was to write:

def expr_match(ob, ed, c=InstanceDict, r=0):
    e, md, push, pop = ed
    push(c(ob, md))
    try:
        r = e.eval(md)
    finally:
        pop()
    return r

which would return r is there is no exception, but allow the exception to propagate if there is one.

@davisagli
Copy link
Member

I agree this should probably be corrected, but in the case of an exception in the try block, I think this raises UnboundLocalError since r hasn't been assigned.

@iritkatriel
Copy link
Author

in the case of an exception in the try block, I think this raises UnboundLocalError since r hasn't been assigned.

In this case it wouldn't reach the 'return r', it will bubble the exception up.

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

No branches or pull requests

2 participants