0

I have a database connection object, and I want to restrict/enforce max number of calls to it's write operation (function). I have mocked it in tests, and have overridden the write method to monitor calls to it.

However, I am confused about what error to raise when it's called more than the max number allowed (say 2). I've gone through the docs but haven't found anything suitable. (Hence, as it suggests) I have used RuntimeError but I am not fully convinced about the message it gives (not the explicit message I display, but the implicit meaning conveyed by the class itself). I feel AttributeError to be a far fit, but nothing else come that close to correctness.

Is there any other builtin exception class which is more suitable for this?

0xc0de
  • 8,028
  • 5
  • 49
  • 75
  • I'd create a custom exception... I am not quite sure why you'd want a builtin though. – UltraInstinct Jul 27 '16 at 06:06
  • @SuperSaiyan Yes, that's my last resort, a pretty common one too. I should have added this line to the question, missed it :). – 0xc0de Jul 27 '16 at 06:27
  • @0xc0de: why would you want to count the number of calls? Do you want to run this code on production? Because you are restricting number of calls to a method which would always throw exception after **MAX** number of calls. It will never open this method till you restart the environment again. – kk. Jul 21 '17 at 14:21

1 Answers1

0

If you supply too many arguments to a function you get something like this:

TypeError: function-name takes exactly n arguments (m given)

So you could do the same to mirror Python. You should probably be careful when you call raise to ensure that your exception string is distinguishable from one raised by Python, otherwise you could mask a genuine TypeError.

Opinion on this is divided. Some say that custom Exception classes are not required. Personally I think there is a place for them if there could be confusion. Creating your own Exception is quite easy, all you need is:

class MyException(TypeError):
    pass

Now you know that any occurrences come from your code, not from Python. Remember if you put this in a module or a class to prefix with the namespace, e.g. MyClass.MyException.

cdarke
  • 42,728
  • 8
  • 80
  • 84