Skip to content

False positive for try-except-raise with multiple exceptions catching #8051

Closed
@fly

Description

@fly

Bug description

Error is produced when a single except statement catches several exceptions for re-raising and when these exceptions are not in the current namespace.

Example (both Exception1 and Exception2 here are inherited directly from Exception):

from app import errors

def check():
    try:
        return do_something()
    except (errors.Exception1, errors.Exception2):  # The except handler raises immediately (try-except-raise)
        raise
    except Exception as e:
        raise errors.Exception1("Boom!") from e

Note that if I bring exceptions directly into namespace, then it works:

from app.errors import Exception1, Exception2

def check():
    try:
        return do_something()
    except (Exception1, Exception2): 
        raise
    except Exception as e:
        raise Exception1("Boom!") from e

It also works if I use separate except statements for each:

from app import errors

def check():
    try:
        return do_something()
    except errors.Exception1:
        raise
    except errors.Exception2:
        raise
    except Exception as e:
        raise errors.Exception1("Boom!") from e

Configuration

No response

Command used

pylint check.py

Pylint output

************* Module check
check.py:19:4: W0706: The except handler raises immediately (try-except-raise)

Expected behavior

No errors

Pylint version

pylint 2.15.10
astroid 2.13.2
Python 3.9.16 (main, Dec  7 2022, 01:12:08) 
[GCC 11.3.0]

OS / Environment

No response

Additional dependencies

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    False Positive 🦟A message is emitted but nothing is wrong with the codeGood first issueFriendly and approachable by new contributorsNeeds PRThis issue is accepted, sufficiently specified and now needs an implementation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions