Suppose in python you have a routine that accepts three named parameters (as **kwargs), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise? RuntimeError, a specifically created exception, or other?
Remember that you can subclass Python's built-in exception classes (and TypeError
would surely be the right built-in exception class to raise here -- that's what Python raises if the number of arguments does not match the signature, in normal cases without *a
or **k
forms in the signature). I like having every package define its own class Error(Exception)
, and then specific exceptions as needed can multiply inherit as appropriate, e.g.:
class WrongNumberOfArguments(thispackage.Error, TypeError):
Then, I'd raise WrongNumberOfArguments
when I detect such a problem situation.
This way, any caller who's aware of this package can catch thispackage.Error
, if they need to deal with any error specific to the package, while other callers (presumably up higher in the call chain) call still catch the more generic TypeError
to deal with any errors such as "wrong number of arguments used in a function call".
Why not just do what python does?
>>> abs(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (3 given)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With