OOP - how to abort an __init__ when the initialisation code fails ?
R.Wieser
address at not.available
Mon Nov 4 15:45:28 EST 2019
Rob,
> That's why if you for instance, open a serial port in an __init__ routine,
> and something fails, you want to catch the exception there in __init__,
> explicitly close that serial port, and reraise the exception. Otherwise
> that port still has an object open against it until Python gets around to
> closing it.
Thats pretty-much the situation I'm trying to jump into (Raspberry Pi, I2C
related).
> The exception you raise should indicate why it failed, such as a TypeError
> or ValueError if one of the arguments was some flavor of stupid, or a
> ConnectionRefusedError.
I'll probably just play it safe, and just recast what the exception I just
caught gave me.
> But if the concern is the try..except block around the initialization
> catching too many things, then either a) your try block is too long and
> encompasses too many unrelated lines of code, or b) your except condition
> is too broad
I was thinking of (the needed) wrapping of the "newObject = classObject()"
line in such a try..except block (to capture the re-casted exception). I
take it that that that means that the full contents of the __init__ block
are wrapped too.
> or b) your except condition is too broad. Don't "except Exception". Only
> catch specific exceptions where you can provide benefit by doing do.
And that means I have to study the "try ... except" methodology a bit more,
as I've currently got only a fleeting knowledge to how it works (including
which error classes it can selectivily catch/filter).
Regards,
Rudy Wieser
More information about the Python-list
mailing list