OOP - how to abort an __init__ when the initialisation code fails ?

Chris Angelico rosuav at gmail.com
Tue Nov 5 05:28:53 EST 2019


On Tue, Nov 5, 2019 at 8:46 PM R.Wieser <address at not.available> wrote:
>
> Chris,
>
> > "Control flow" is anything that changes the order that your code runs.
>
> My apologies, I should have said "a control flow mechanism" /in this
> context/ (though I assumed that as implicite, as I quoted the text from the
> OP).
>
> Case in point, the __init__ code (of a class object) can result in an
> exception, and I need to deal with it.  But I should /not/ wrap whole blocks
> of code into a "try ... except" construction - which definitily is what will
> happen when I want to catch, in the calling program, exceptions thrown by
> the object while its initialising.
>
> So, I was wondering if the "a control flow mechanism" reference was aimed at
> something that would alleviate the above "you must, but you shouldn't"
> conundrum.
>

Gotcha.

The usual solution to this conundrum is a specific exception. You
don't have to catch all arbitrary exceptions that might be thrown; you
can define your own custom exception and catch only that. That way,
you can use "raise SomeSpecificException" as a form of control flow,
without disrupting the ability to detect other sorts of errors.

ChrisA


More information about the Python-list mailing list