What is the analog for .Net InvalidOperationException in Python?
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.
There's no direct equivalent. Usually ValueError
or TypeError
suffices, perhaps a RuntimeError
or NotImplementedError
if neither of those fit well.
I'd probably go between one of two options:
A custom exception, best defined as follows:
class InvalidOperationException(Exception): pass
Just using
Exception
I don't believe there's a direct analogue; Python seems to have a very flat exception hierarchy.