I implemented a python class for which the instances are stored in a h5-file. As such, the __init__()-function of this class first checks if this h5-file yet exists from a previous simulations, and if so raises a raw_input asking to overwrite this file (whereafter the file is overwritten by the new instance) or not, whereafter an error is raised.
I am looking for a way that, when this file (and thus instance) already exists and this is noted in the __init__()-method, i don’t raise an Error whereafter the script stops, buta way to “cancel” the started instantiation and the script just continues … Is there a clean way to implement such “cancel and ocntinue” ?
The right way to do it is to raise an exception. By default, the exception will propagate out from the
__init__to whoever called it, and eventually all the way to the top, halting the script.But if you want to handle that exception and continue, use a
try/catchblock at whatever level you want to continue from, as described in Handling Exceptions.For example:
If you want to catch this before even getting to the
__init__, you could always do the check in the__new__method, or in a@classmethodfactory function, or in theforloop, in which case you don’t even need an exception; just don’t initialize. But there’s nothing stopping you from raising an exception inside__init__.