views:

46

answers:

3

What is the analog for .Net InvalidOperationException in Python?

+1  A: 

I'd probably go between one of two options:

  1. A custom exception, best defined as follows:

    class InvalidOperationException(Exception): pass

  2. Just using Exception

I don't believe there's a direct analogue; Python seems to have a very flat exception hierarchy.

Chris R
A: 

There's no direct equivalent. Usually ValueError or TypeError suffices, perhaps a RuntimeError or NotImplementedError if neither of those fit well.

Ignacio Vazquez-Abrams
+1  A: 

I'll partially agree with Chris R -- define your own:

     class InvalidOperationException(Exception): pass

You get much benefit from defining your own exceptions this way, including building a hierarchy to fit your needs:

     class MyExceptionBase(Exception): pass
     class MyExceptionType1(MyExceptionBase): pass
     class MyExceptionType2(MyExceptionBase): pass
     # ...
     try:
        # something
     except MyExceptionBase, exObj:
        # handle several types of MyExceptionBase here...

I don't agree with throwing a naked "Exception", though.

Kevin Little