It is true that the only correct way to indicate an error in the constructor is to throw an exception. That is why in C ++ and in other object-oriented languages ββthat were developed taking into account the safety of exceptions, the destructor is not called if the exception is selected in the constructor of the object (which means that the initialization of the object is incomplete). This is often not the case in scripting languages ββsuch as Python. For example, the following code throws an AttributeError if socket.connect () fails:
class NetworkInterface: def __init__(self, address) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(address) self.stream = self.socket.makefile() def __del__(self) self.stream.close() self.socket.close()
The reason is that the incomplete object destructor is called after the connection attempt failed before the thread attribute was initialized. You should not avoid throwing exceptions from constructors, I am just saying that it is difficult to write completely safe exception code in Python. Some Python developers generally avoid using destructors, but this is a matter of other debate.
Seppo Enarvi Sep 21 2018-11-21T00: 00Z
source share