[Tutor] raising exceptions in constructor code?

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jul 16 18:49:12 EDT 2019


On 16/07/2019 22:56, Mats Wichmann wrote:

>> thrown.  This gets watered down to the mantra "Don't throw exceptions from
>> within constructors."  Does this carry over to Python?  

> 
> If you mean __init__, that's not a constructor, so you should set your
> mind at rest :)   It's more properly an "initializer", the instance has
> already been constructed when it's called.

FWIW The true constructor is __new__() and its quite rarely overridden
by application programmers. But if you do, it's not common that you'd do
anything that would merit an exception. __new__ pretty much just sets
up the structure of the object ready for initialisation by __init__.

Incidentally, this two stage construction/initialisation is also found
in other OOP languages like Smalltalk and Objective C (and Lisp?).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list