Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object not in the right state; which exception is appropriate?

Say I have a

class Rocket(object):
    def __init__(self):
        self.ready = False

    def prepare_for_takeoff(self):
        self.ready = True

    def takeoff(self):
        if not self.ready:
            raise NotReadyException("not ready!")
        print("Liftoff!")

Now, which of the standard exceptions would be most appropriate to derive NotReadyException from? Would it be ValueError, since self has the wrong state/value?

like image 494
Fred Foo Avatar asked Jan 19 '23 16:01

Fred Foo


2 Answers

Now, which of the standard exceptions would be most appropriate to derive NotReadyException from?

Exception

Don't mess with anything else.

http://code.google.com/p/soc/wiki/PythonStyleGuide#Exceptions

What are your use cases for exception handling?

If you derived your exception from, say ValueError, would you ever write a handler that used except ValueError: to catch both exceptions and handle them in exactly the same way? Unlikely.

ValueError is a catch-all when more specific exceptions aren't appropriate. Your exception is very specific.

When you have an application-specific exception like this, the odds of it sharing any useful semantics with a built-in exception are low. The odds of actually combining the new one and an existing exception into a single handler are very, very low.

About the only time you'll ever combine an application-specific exception with generic exceptions is to use except Exception: in some catch-all logger.

like image 76
S.Lott Avatar answered Feb 15 '23 23:02

S.Lott


I'd just derive it from Exception. Programmers who catch ValueError might be quite surprised that they catch your NotReadyException as well.

If you will be defining a lot of similar types of state-related exceptions, and it would be convenient to be able to catch 'em all, you might define a StateError exception and then derive NotReadyException from that.

like image 32
kindall Avatar answered Feb 15 '23 22:02

kindall