views:

242

answers:

6

Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?

+1  A: 

I should think it is the perfect case for the built-in ValueError exception.

Teddy
+1  A: 

The standard library says:

>>> f = file("notexisting.txt")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'notexisting.txt'

Also I don't really see any reason why it should be considered bad form.

sth
+11  A: 

Raising exceptions within __init__() is absolutely fine. There's no other good way to indicate an error condition within a constructor, and there are many hundreds of examples in the standard library where building an object can raise an exception.

The error class to raise, of course, is up to you. ValueError is best if the constructor was passed an invalid parameter.

John Millikin
The most used exceptions in constructor are `ValueError` and `TypeError`.
Denis Otkidach
+5  A: 

I don't see any reason that it should be bad form.

On the contrary, one of the things exceptions are known for doing well, as opposed to returning error codes, is that error codes usually can't be returned by constructors. So at least in languages like C++, raising exceptions is the only way to signal errors.

Edan Maor
+1  A: 

I concur with all of the above.

There's really no other way to signal that something went wrong in the initialisation of an object other than raising an exception.

In most programs classes where the state of a class is wholly dependant on the inputs to that class we might expect some kind of ValueError or TypeError to be raised.

Classes with side-effects (e.g. one which does networking or graphics) might raise an error in init if (for example) the network device is unavailable or the canvas object cannot be written to. This sounds sensible to me because often you want to know about failure conditions as soon as possible.

Salim Fadhley
A: 

Exceptions are our friend :)

John Giotta
and non-answers are not.
SilentGhost