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

suggestion: On exception raising #15

Open
OmAximani0 opened this issue May 23, 2023 · 0 comments
Open

suggestion: On exception raising #15

OmAximani0 opened this issue May 23, 2023 · 0 comments

Comments

@OmAximani0
Copy link

I saw the code raises many exception from class Exception. First, the only way to handle differently multiple Exceptions is to check their message, which is error-prone and difficult to maintain.

def process1():
    raise BaseException("Wrong user input for field X")  # Noncompliant

def process2():
    raise BaseException("Wrong configuration")  # Noncompliant

def process3(param):
    if not isinstance(param, int):
        raise Exception("param should be an integer")  # Noncompliant

def caller():
    try:
         process1()
         process2()
         process3()
    except BaseException as e:
        if e.args[0] == "Wrong user input for field X":
            # process error
            pass
        elif e.args[0] == "Wrong configuration":
            # process error
            pass
        else:
            # re-raise other exceptions
            raise

Standard Recommendation :

  • raise a more specific Built-in exception when one matches. For example TypeError should be raised when the type of a parameter is not the one expected.
  • create a custom exception class deriving from Exception or one of its subclasses. A common practice for libraries is to have one custom root exception class from which every other custom exception class inherits. It enables other projects using this library to catch all errors coming from the library with a single "except" statement
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

1 participant