rbiparser
rbiparser copied to clipboard
suggestion: On exception raising
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