Skip to content

Detect unreachable except branches #11514

Description

@jcrist

Since except blocks are checked in order, and the first matching block is executed, it's possible to accidentally write a try-except that will never execute some branches. For example:

def bad_reader(path: str) -> bytes:
    if path == "bad":
        raise PermissionError

    with open(path, "rb") as f:
        return f.read()


def load_data(path: str) -> bytes:
    try:
        return bad_reader(path)
    except OSError:
        print("OSError caught")
    except PermissionError:
        # This branch will never be hit, since `OSError` will always catch
        # permission error
        print("PermissionError caught")

    return b""


load_data("bad")

Since PermissionError is a subclass of OSError, the except PermissionError case will never execute. I'd expect/hope that these kind of mistakes would be detectable with type information. I think adding checks for this would make sense under the --warn-unreachable config flag, so a new CLI option may not be needed.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions